如何使用逗号分隔列值

时间:2013-02-07 07:27:28

标签: sql sql-server

我有来自Grouping表的表Sensor Groupid(PK),Sensorid(FK)。 并且Sensor表具有Unitid作为外键引用。 所以我使用这个查询来获取三个表中的所有列:

  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,所以它会抛出无效的列错误。

1 个答案:

答案 0 :(得分: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 Fiddle Demo

这会给你:

| GROUP | UNIT |    SENSORS |
-----------------------------
|    G1 |   U1 | S1, S4, S3 |
|    G1 |   U2 |     S2, S5 |
|    G2 |   U1 |         S7 |