【问题标题】:SQL Group by with concatSQL Group by 与 concat
【发布时间】:2011-06-21 02:44:52
【问题描述】:

嗨 任何人都可以帮我解决以下问题。我需要编写一个 MS SQL 语句来实现以下目标:

Table1 有 2 列:Column1Column2

table1 中的数据看起来像

Column1   Column2
1         a
1         b
1         c
2         w
2         e
3         x

我需要我的 Sql 语句输出如下

Column1   Column2
1         a, b, c
2         w, e
3         x

换句话说,我需要按 column1 分组,并将 column2 值用逗号分隔连接。请注意,这需要能够在 SQL Server 2000 及更高版本上运行

【问题讨论】:

  • 对不起,我试图显示包含两列(Column1 和 Column2)的示例表,不知道为什么它没有正确显示
  • 每行缩进 4 个空格,它会排成一行。

标签: sql tsql sql-server-2000 group-by concat


【解决方案1】:

您可以创建一个函数来连接值

create function dbo.concatTable1(@column1 int) returns varchar(8000)
as
begin
declare @output varchar(8000)
select @output = coalesce(@output + ', ', '') + column2
from table1
where column1 = @column1 and column2 > ''
return @output
end
GO

所以假设你有这张桌子

create table table1 (column1 int, column2 varchar(10))
insert table1 select 1, 'a'
insert table1 select 1, 'b'
insert table1 select 1, 'c'
insert table1 select 2, 'w'
insert table1 select 2, 'e'
insert table1 select 3, 'x'
GO

你是这样用的

select column1, dbo.concatTable1(column1) column2
from table1
group by column1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-09-22
    • 2022-12-01
    • 2016-03-06
    • 2012-10-02
    • 1970-01-01
    • 2019-02-11
    • 2018-04-11
    • 2010-09-30
    相关资源
    最近更新 更多