1

我从表中有表GroupingGroupid(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,因此会引发无效列错误。

4

1 回答 1

1

在 SQL Server 中,没有内置的方法来执行此操作,但是,您可以使用FOR XML来执行此操作:

WITH CTE
AS
(
  -- Put your query here
)
SELECT 
  t1."Group",
  t1.Unit ,
  STUFF((
    SELECT ', ' + t2.Sensor  
    FROM CTE t2
    WHERE t2."Group" = t1."Group"
      AND t2.Unit = t1.Unit
    FOR XML PATH (''))
  ,1,2,'') AS Sensors
FROM CTE t1
GROUP BY t1."Group", 
         t1.Unit;

SQL 小提琴演示

这会给你:

| GROUP | UNIT |    SENSORS |
-----------------------------
|    G1 |   U1 | S1, S4, S3 |
|    G1 |   U2 |     S2, S5 |
|    G2 |   U1 |         S7 |
于 2013-02-07T07:34:47.290 回答