SQL Group by 和 concat

标签 sql t-sql sql-server-2000 group-by concatenation

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

Table1 有 2 列:Column1Column2

表1中的数据看起来像

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

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

最佳答案

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

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

假设你有这张 table

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

关于SQL Group by 和 concat,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4894095/

相关文章:

sql-server-2005 - 将 SQL Server 数据库从 2005 转换为 2000

asp-classic - 针对 SQL 注入(inject)的经典 ASP 保护

sql - 需要评论策略

MySQL 字段保存发货国家/地区列表

SQL Server 对行进行分组

c# - 我应该如何研究 'rotate'或 'flatten'这个数据? PIVOT、自连接还是其他?

sql - 如何获取 SQL Server 中给定一天的日期范围之间的日期

sql - 如何有效地检索树中节点的路径(与帖子 'parse a flat table into a tree?' 相关)

mysql - SQL/MySQL 递归地从同一个表中提取

VB6 Activex组件无法创建对象