create table tb(id int, a varchar(20), 用户id int, type int)
insert into tb values(1 , '3(网站来源)' , 101 , 24 )
insert into tb values(2 , '5(DB来源)' , 101 , 10)
insert into tb values(3 , '3(其他来源)' , 101 , 3 )
insert into tb values(4 , '3' , 102 , 5 )
insert into tb values(5 , '8' , 103 , 120)
insert into tb values(6 , '5' , 101 , 32)
insert into tb values(7 , '3' , 102 , 34)
insert into tb values(8 , '5' , 103 , 5)
insert into tb values(9 , '8' , 102 , 4 )
goselect 用户id ,
max(case when charindex('网站来源',a) > 0 then left(a,1) + right('00'+cast(type as varchar),2) else '0' end) 网站来源,
max(case when charindex('DB来源',a) > 0 then left(a,1) + right('00'+cast(type as varchar),2) else '0' end) DB来源,
max(case when charindex('其他来源',a) > 0 then left(a,1) + right('00'+cast(type as varchar),2) else '0' end) 其他来源
from tb
group by 用户iddrop table tb/*
用户id 网站来源 DB来源 其他来源
----------- ------ ------ ------
101 324 510 303
102 0 0 0
103 0 0 0(所影响的行数为 3 行)
*/
insert into tb values(1 , '3(网站来源)' , 101 , 24 )
insert into tb values(2 , '5(DB来源)' , 101 , 10)
insert into tb values(3 , '3(其他来源)' , 101 , 3 )
insert into tb values(4 , '3' , 102 , 5 )
insert into tb values(5 , '8' , 103 , 120)
insert into tb values(6 , '5' , 101 , 32)
insert into tb values(7 , '3' , 102 , 34)
insert into tb values(8 , '5' , 103 , 5)
insert into tb values(9 , '8' , 102 , 4 )
goselect 用户id ,
max(case when charindex('网站来源',a) > 0 then left(a,1) + right('00'+cast(type as varchar),2) else '0' end) 网站来源,
max(case when charindex('DB来源',a) > 0 then left(a,1) + right('00'+cast(type as varchar),2) else '0' end) DB来源,
max(case when charindex('其他来源',a) > 0 then left(a,1) + right('00'+cast(type as varchar),2) else '0' end) 其他来源
from tb
group by 用户iddrop table tb/*
用户id 网站来源 DB来源 其他来源
----------- ------ ------ ------
101 324 510 303
102 0 0 0
103 0 0 0(所影响的行数为 3 行)
*/
用户id
,sum(case when a字段 = 3 then type + 300 else 0 end) as 网站来源
,sum(case when a字段 = 5 then type + 500 else 0 end) as DB来源
,sum(case when a字段 = 8 then type + 800 else 0 end) as 其他来源
from A表
group by 用户id
insert into tb values(1 , '3' , 101 , 24 )
insert into tb values(2 , '5' , 101 , 10)
insert into tb values(3 , '3' , 101 , 3 )
insert into tb values(4 , '3' , 102 , 5 )
insert into tb values(5 , '8' , 103 , 120)
insert into tb values(6 , '5' , 101 , 32)
insert into tb values(7 , '3' , 102 , 34)
insert into tb values(8 , '5' , 103 , 5)
insert into tb values(9 , '8' , 102 , 4 )
goselect 用户id ,
max(case a when '3' then 300 + type else 0 end) 网站来源,
max(case a when '5' then 500 + type else 0 end) DB来源,
max(case a when '8' then 800 + type else 0 end) 其他来源
from tb
group by 用户iddrop table tb/*用户id 网站来源 DB来源 其他来源
----------- ----------- ----------- -----------
101 324 532 0
102 334 0 804
103 0 505 920(所影响的行数为 3 行)
*/