合并表法

  1. /*合并法系列*/
  2. --合并法(函数)
  3. create table tb1
  4. (
  5.   col1 varchar(10),
  6.   col2 int
  7. )
  8. insert into tb1 select 'a',1
  9. union all select 'a',2
  10. union all select 'b',1
  11. union all select 'b',2
  12. union all select 'b',3
  13. create function dbo.FC_Str(@col1 varchar(100))
  14. returns varchar(100)
  15. as
  16. begin
  17.    declare @i varchar(100)
  18.    set @i=''
  19.    select @i=@i+','+cast(col2 as varchar) from tb1 where col1=@col1
  20.    return(stuff(@i,1,1,''))
  21. end
  22. select col1,dbo.FC_Str(col1) from tb1 group by col1
  23. --固定行合并法
  24. create table #tb
  25. (
  26.   col1 varchar(10),
  27.   col2 int
  28. )
  29. insert into #tb select 'a',1
  30. union all select 'a',2
  31. union all select 'b',1
  32. union all select 'b',2
  33. union all select 'c',3
  34. select col1,
  35.        col2=cast(min(col2) as varchar)+
  36.        case when count(*)=1 then ''
  37.        else +','+cast(max(col2) as varchar) end from #tb
  38. group by col1
  39. --临时表合并法
  40. if object_id('tb'is not null drop table tb
  41. create table tb
  42. (
  43.   col1 varchar(10),
  44.   col2 int
  45. )
  46. insert into tb select 'a',1
  47. union all select 'a',2
  48. union all select 'b',1
  49. union all select 'b',2
  50. union all select 'b',3
  51. select col1,col2=cast(col2 as varchar(100)) into #t1 from tb order by col1,col2
  52. declare @col1 varchar(20)
  53. declare @col2 varchar(100)
  54. update #t1 set @col2=
  55.                    case when @col1=col1 then @col2+ ',' +col2
  56.                    else col2 end,
  57.            @col1=col1,
  58.            col2=@col2
  59. select * from #t1
  60. select col1,col2=max(col2) from #t1 group by col1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值