现有一个表,结构及数据如下:
id money type (无主键,无重复行)
1 111 a
1 222 b
1 333 c
欲实现如下效果,sql怎么写?
id a b c
1 111 222 333
先暂时只考虑type就只有a,b,c 三种类型;
当type存在多种类型时,例如还有一类d,那么我想实现结果集(id,a,b,c,d),该怎么做?
...全文
1905打赏收藏
求一条sql语句。。。
现有一个表,结构及数据如下: id money type (无主键,无重复行) 1 111 a 1 222 b 1 333 c 欲实现如下效果,sql怎么写? id a b c 1 111 222 333 先暂时只考虑type就只有a,b,c 三种类型; 当type存在多种类型时,例如还有一类d,那么我想实现结果集(id,a,b,c,d),该怎么做?
if object_id('tb') is not null
drop table tb
go
create table tb(id int,money int,type varchar(10))
insert tb
select 1,111,'a' union all
select 1,222,'b' union all
select 1,333,'c'
----静态写法
select id,
a=sum(case type when 'a' then money else 0 end),
b=sum(case type when 'b' then money else 0 end),
c=sum(case type when 'c' then money else 0 end)
from tb group by id
----动态写法(适合"当type存在多种类型时,例如还有一类d,那么我想实现结果集(id,a,b,c,d),该怎么做?")
declare @str varchar(2000)
set @str = ''
select @str = @str + ',' + type + '=sum(case type when ''' + type + ''' then money else 0 end)'
from (select distinct type from tb) a /*去掉重复的type*/
--print @str
----执行汇总
exec ('select id '+ @str + ' from tb group by id')