我认为用一个例子可以更容易地解释这一点,所以假设我们有这样一个数据库:
Interventions
,它存储Id和它需要的任何东西。Doctors
。Tools
。DoctorsOnInterventions
ToolsOnInterventions
好吧,现在我们可以:
SELECT InterventionId, STRING_AGG(Doctors.Name, ', ')
FROM Interventions
INNER JOIN Doctors ON Doctors.Id = DoctorsOnInterventions.DoctorId
GROUP BY Intervention.Id, Doctors.Id;
并得到:
+-----------------+------------+
| InterventionId | Doctors |
+-----------------+------------+
| 1 | Tom, John |
| 2 | Tom, Homer |
+-----------------+------------+
但是我们需要增加另一个专栏,就像医生一样,但是在干预中使用的工具是这样的:
+-----------------+------------+-----------------+
| InterventionId | Doctors | Tools |
+-----------------+------------+-----------------+
| 1 | Tom, John | Scalpel, Hammer |
| 2 | Tom, Homer | Hammer, Bulb |
+-----------------+------------+-----------------+
将前面的代码包装在子查询上,然后再创建另一个group by
是很容易的,但是我想知道是否有更正确的方法来实现这一点,因为我的数据库表有几十个列。
发布于 2019-02-26 10:25:23
SELECT InterventionId, STRING(Doctors.Name, ', '),STRING(Tools.name,',')
FROM Interventions
INNER JOIN Doctors ON Doctors.Id = DoctorsOnInterventions.DoctorId
INNER JOIN Tools on tools.id = ToolsOnInterventions.toolsid
GROUP BY Intervention.Id, Doctors.Id, tools.id;
发布于 2019-02-26 08:13:30
您可以使用string_agg()
。我建议使用子查询;可以使用apply
:
SELECT i.*, d.doctors, t.tools
FROM Interventions i OUTER APPLY
(SELECT STRING_AGG(d.name, ',') as doctors
FROM DoctorsOnInterventions doi JOIN
Doctors d
ON d.Id = doi.DoctorId
WHERE doi.interventionId = i.id
) d OUTER APPLY
(SELECT STRING_AGG(t.name, ',') as tools
FROM ToolsOnInterventions toi JOIN
Tools t
ON t.id = toi.ToolId
WHERE toi.interventionId = i.id
) t ;
在Server的旧版本中,可以使用字符串连接的FOR XML PATH
方法。
发布于 2019-02-26 08:19:08
我想你需要另一张桌子。
表式干预
+-----------------+------------+
| InterventionId | Doctors |
+-----------------+------------+
| 1 | Tom, John |
| 2 | Tom, Homer |
+-----------------+------------+
表工具
+-----------------+----------------+
| InterventionId | Doctors |
+-----------------+----------------+
| 1 | Scalpel, Hammer|
| 2 | Hammer, Bulb |
+-----------------+----------------+
表Interventions_tool (新)
+-----------------+------------+
| InterventionId | ToolId |
+-----------------+------------+
| 1 | 1 |
| 2 | 2 |
+-----------------+------------+
查询将是
SELECT InterventionId, STRING(Doctors.Name, ', ')
FROM Interventions I WITH (NOLOCK)
INNER JOIN Doctors D WITH (NOLOCK) ON D.Id = I.DoctorId
INNER JOIN Interventions_tool IT WITH (NOLOCK) ON I.Id = IT.ToolId
GROUP BY I.Id, D.Id;
+-----------------+------------+-----------------+
| InterventionId | Doctors | Tools |
+-----------------+------------+-----------------+
| 1 | Tom, John | Scalpel, Hammer |
| 2 | Tom, Homer | Hammer, Bulb |
+-----------------+------------+-----------------+
https://stackoverflow.com/questions/54889632
复制相似问题