我从表中有表Grouping
Groupid(PK)、Sensorid(FK) Sensor
。并且Sensor
表具有 Unitsid 作为外键引用。所以我使用这个查询从三个表中获取所有列:
Select * from Grouping
left join Sensors on Grouping.SensorID = Sensors.SensorID
left joinUnits on Grouping.UnitsID = Units.UnitsID
输出:
Group Unit Sensor
G1 U1 S1
G1 U2 S2
G1 U1 S4
G1 U1 S3
G1 U2 S5
G2 U1 S7
我的问题是我想要这样的输出:
G1 U1 S1,S3,S4
G1 U2 S2,S5
G2 U1 S7
如何从“分组”表中获取此输出?
WITH CTE
AS
(
Select * fromGrouping
left join Sensors on Grouping.SensorID = Sensors.SensorID
left join Units onGrouping.UnitsID = Units.UnitsID
)
SELECT
t1."Group",
t1.Unit ,
STUFF((
SELECT ', ' + t2.Sensor
FROM Grouping t2
WHERE t2."Group" = t1."Group"
AND t2.Unit = t1.Unit
FOR XML PATH (''))
,1,2,'') AS Sensors
FROM Grouping t1
GROUP BY t1."Group", t1.Unit;
这不起作用,因为分组表只有sensorId和unitsId,因此会引发无效列错误。