MSSQL 使用临时表实现字符串合并处理

-->Title:Generating test data

-->Author:wufeng4552

-->Date :2009-09-30 15:16:26

if object_id('tb')is not null drop table tb

go

CREATE TABLE tb(col1 varchar(10),col2 int)

INSERT tb SELECT 'a',null

UNION ALL SELECT 'a',null

UNION ALL SELECT 'b',null

UNION ALL SELECT 'b',null

declare @col1 varchar(10)

declare @col2 int

update tb set @col2=case when @col1=col1 then @col2+1 else 1 end,

@col1=col1,col2=@col2

--每组 <=2 条的合并

select col1,

col2=ltrim(min(col2))+case when count(*)=1 then ''

else ','+ltrim(max(col2)) end

from tb group by col1

/*

col1 col2

---------- -------------------------

a 1,2

b 1,2

*/

--每组 <=3 条的合并

insert tb select 'b',3

select col1,

col2=CAST(MIN(col2) as varchar)

+CASE

WHEN COUNT(*)=3 THEN ','

+CAST((SELECT col2 FROM tb WHERE col1=a.col1 AND col2 NOT IN(MAX(a.col2),MIN(a.col2))) as varchar)

ELSE ''

END

+CASE

WHEN COUNT(*)>=2 THEN ','+CAST(MAX(col2) as varchar)

ELSE ''

END

from tb a group by col1

/*

col1 col2

---------- ---------------------

a 1,2

b 1,2,3

*/

if object_id('tempdb..#')is not null drop table #

go

select col1,

ltrim(col2)col2

into # from tb order by col1,col2

declare @col1 varchar(10)

declare @col2 varchar(20)

update # set @col2=case when @col1=col1 then @col2+','+col2 else col2 end,

@col1=col1,

col2=@col2

go

select col1,

max(col2)col2

from # group by col1

/*

col1 col2

---------- ------------

a 1,2

b 1,2,3

*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值