⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 合并字符串.txt

📁 SQL语言常用的一些命令各代码
💻 TXT
字号:
tab1
c1 c2
--- ---
001 a
001 b
001 c
002 a
002 b
003 b
...
现在想实现如下的格式
c1 c2
--- ---
001 a,b,c
002 a,b
003 b
请问如何用SQL解决,不胜感激

/*解答:*/
create table tab1(c1 varchar(5),c2 char(1))
insert into tab1 select '0001','a'
union all        select '0001','b'
union all        select '0001','c'
union all        select '0002','a'
union all        select '0002','b'
union all        select '0003','b'

declare @A table(a int identity(1,1),c1 varchar(5),c2 char(1))
insert into @A(c1,c2)
select c1,c2 from tab1 order by c1 desc
declare @anser table (c1 varchar(5),c2 varchar(10))
declare @b varchar(5),@c varchar(10),@d int
select @b=(select min(c1) from tab1)
while @b<=(select max(c1) from tab1)
begin
select @d=(select min(a) from  (select a from @A where c1=@b) X)
select @c=''        
          while @d<=(select max(a) from  (select a from @A where c1=@b) X)
            begin
            select @c=@c+(select c2 from @A where c1=@b and a=@d)+','
            select @d=(select min(a) from (select a from @A where c1=@b and a>@d) X)
            end
 insert into @anser select @b,left(@c,len(@c)-1)
 select @b=(select min(c1) from tab1 where c1>@b)
end
select * from @anser

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -