1

这是我使用多层SELECT查询检索的数据:

TID StartID EndID   StartTime               EndTime                 ResName
1   1491005 1491020 2013-07-15 06:43:50.000 2013-07-15 06:44:38.000 NULL
1   1501403 1502819 2013-07-15 12:52:41.000 2013-07-15 13:40:10.000 TT Bill
1   1490838 1508632 2013-07-15 06:35:25.000 2013-07-15 16:57:10.000 TA Brady-MGR
1   1491039 1491267 2013-07-15 06:45:32.000 2013-07-15 06:56:35.000 TA Larry-Drv
2   1508739 1508939 2013-07-15 07:33:32.000 2013-07-15 07:44:35.000 TN John

我需要按TIDGROUP处理此数据,以便所有具有相同TID的ResName值都显示为逗号分隔值。

例如:对于TID 1,最后一列TIDNames的值必须是TT Bill,TA Brady, TA Larry

我正在使用以下查询进行GROUPING

    Select G.TID,
    Min(G.StartId) As MinSID, Max(G.EndId) As MaxSID, 
    Min(G.StartTime) As MinStartTime, Max(G.EndTime) As MaxStartTime,
    'I need comma separated ResName values for my TID here' As TIDNames
    From ( 
           nested select - this is where I get the above data which needs further grouping
    ) G
    Group By G.TID;

我试图在这个小提琴中模拟这种场景(而不是嵌套选择,我将数据存储在一个表中):http ://sqlfiddle.com/#!3/f3267/1

4

1 回答 1

2

您可以使用 FOR XML PATH 将值连接成一行:

Select t1.TID,
  Min(t1.StartId) As MinSID, 
  Max(t1.EndId) As MaxSID, 
  Min(t1.StartTime) As MinStartTime, 
  Max(t1.EndTime) As MaxStartTime,
  STUFF((SELECT ', ' + t2.ResName
          FROM Item t2
          where t1.TID = t2.TID
          FOR XML PATH (''))
          , 1, 1, '')  AS TIDNames
From Item t1
Group By t1.TID;

请参阅SQL Fiddle with Demo

如果您查询的数据来自另一个查询,那么您可以使用 CTE:

;with cte as
(
  select * from yourqueryHere
) 
select t1.TID,
  Min(t1.StartId) As MinSID, 
  Max(t1.EndId) As MaxSID, 
  Min(t1.StartTime) As MinStartTime, 
  Max(t1.EndTime) As MaxStartTime,
  STUFF((SELECT ', ' + t2.ResName
          FROM cte t2
          where t1.TID = t2.TID
          FOR XML PATH (''))
          , 1, 1, '')  AS TIDNames
From cte t1
Group By t1.TID;

请参阅带有演示的 SQL Fiddle

于 2013-07-22T20:43:28.740 回答