1

私のクエリは次のとおりです。

select 
gp.GroupName+ '' As GroupName,  
us.UnitsName+'' As Unitname,
sp.Sensorname+',' As sensorName
from Grouping as gp
inner join Units as us
on gp.UnitsID = us.UnitsID
inner join Sensors as sp
on gp.SensorID = sp.SensorID

出力は

GroupName   Unitname    sensorName

G1         Electricity  S1,

G1        Electricity   S3,

G2          Gas       test,

しかし、出力は次のようになります

G1         Electricity  S1,S3

G2          Gas       test

それを取得する方法は?

4

1 に答える 1

1
WITH CTE
AS
(
    select
      gp.GroupName  As GroupName,
      us.UnitsName  As Unitname,
      sp.Sensorname As sensorName
    from Grouping as gp
    inner join Units as us  on gp.UnitsID = us.UnitsID
    inner join Sensors as sp on gp.SensorID = sp.SensorID
)
SELECT 
  c1.Groupname,
  c1.Unitname,
  STUFF((
    SELECT ', ' + c2.sensorName
    FROM CTE c2
    WHERE c2.GroupName = c1.GroupName
      AND c2.Unitname = c1.Unitname
    FOR XML PATH (''))
  ,1,2,'') AS Sensors
FROM CTE  c1
GROUP BY c1.GroupName,
         c1.Unitname;
于 2013-02-07T11:20:54.163 に答える