使用字符串值对id进行分组,而不是整数SQL GROUP BY

时间:2011-05-14 08:42:48

标签: sql sql-server sql-server-2008 group-by

在谷歌上我刚刚找到了sum(整数值)组。如何按字符串值分组?对于表格:

No   Place    Car 
---  ------   --------
1    NY       VRM1
1    BT       VLI
2    NY       GAR
3    GT       GAR

如何按“否”分组?我试过了:

SELECT No, place, Car 
FROM  APPEL
GROUP BY No, Place, Car

但它不起作用。

我想要一张这样的表

No   Place    Car 
---  ------   --------
1    NY,BT    VRM1,VLI
2    NY       GAR
3    GT       GAR

1 个答案:

答案 0 :(得分:4)

-- Sample data
with T (No,   Place,    Car) as
(
select 1,    'NY',       'VRM1' union all
select 1,    'BT',       'VLI' union all
select 2,    'NY',       'GAR' union all
select 3,    'GT',       'GAR'
)

-- The query
select
  T.No,
  stuff((select ','+T2.Place
         from T as T2 
         where T.No = T2.No
         for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Place,
  stuff((select ','+T2.Car
         from T as T2 
         where T.No = T2.No
         for xml path(''), type).value('.', 'nvarchar(max)'), 1, 1, '') as Car
from T
group by T.No