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

发布于 2024-11-07 08:45:57 字数 454 浏览 0 评论 0原文

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

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

On Google I just found group by sum (integer value). How can I group by a string value? For the table:

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

How can I group by 'No'? I tried:

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

But it didn't work.

I want to have a table like this

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

苍风燃霜 2024-11-14 08:45:57
-- 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
-- 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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文