日期:2014-05-18 浏览次数:20784 次
if object_id('tb') is not null
drop table tb
go
create table tb
(
id int identity(1,1),
名称 varchar(10),
分类 int,
编码 int,
用户ID int
)
go
insert into tb(名称,分类,编码,用户ID)
select 'A',1,1,1111 union all
select 'B',1,0,3333 union all
select 'C',2,0,3333 union all
select 'D',3,0,3333 union all
select 'E',3,0,4444 union all
select 'F',3,0,4444
go
select 用户ID,
分类1编码0的数据=sum(case when 分类=1 and 编码=0 then 1 else 0 end),
分类1编码1的数据=sum(case when 分类=1 and 编码=1 then 1 else 0 end),
分类2编码0的数据=sum(case when 分类=2 and 编码=0 then 1 else 0 end),
分类2编码1的数据=sum(case when 分类=2 and 编码=1 then 1 else 0 end),
分类3编码0的数据=sum(case when 分类=3 and 编码=0 then 1 else 0 end),
分类3编码1的数据=sum(case when 分类=3 and 编码=1 then 1 else 0 end)
from tb
group by 用户ID
go
/*
用户ID 分类1编码0的数据 分类1编码1的数据 分类2编码0的数据 分类2编码1的数据 分类3编码0的数据 分类3编码1的数据
----------- ----------- ----------- ----------- ----------- ----------- -----------
1111 0 1 0 0 0 0
3333 1 0 1 0 1 0
4444 0 0 0 0 2 0
(3 行受影响)
*/
------解决方案--------------------
select 用户id,
sum(case when 分类 = 1 and 编码 = 0 then 1 else 0 end) [分类1编码0的数据],
sum(case when 分类 = 1 and 编码 = 1 then 1 else 0 end) [分类1编码1的数据],
sum(case when 分类 = 2 and 编码 = 0 then 1 else 0 end) [分类2编码0的数据],
sum(case when 分类 = 2 and 编码 = 1 then 1 else 0 end) [分类2编码1的数据],
sum(case when 分类 = 3 and 编码 = 0 then 1 else 0 end) [分类3编码0的数据],
sum(case when 分类 = 3 and 编码 = 1 then 1 else 0 end) [分类3编码1的数据]
from [table]
group by 用户id
------解决方案--------------------
create table [table](id int,名称 varchar(10),分类 int,编码 int,用户ID int)
insert into [table] values(1 ,'A', 1 ,1 ,1111)
insert into [table] values(2 ,'B', 1 ,0 ,3333)
insert into [table] values(3 ,'C', 2 ,0 ,3333)
insert into [table] values(4 ,'D', 3 ,0 ,3333)
insert into [table] values(5 ,'E', 3 ,0 ,4444)
insert into [table] values(6 ,'F', 3 ,0 ,4444)
go
select 用户id,
sum(case when 分类 = 1 and 编码 = 0 then 1 else 0 end) [分类1编码0的数据],
sum(case when 分类 = 1 and 编码 = 1 then 1 else 0 end) [分类1编码1的数据],
sum(case when 分类 = 2 and 编码 = 0 then 1 else 0 end) [分类2编码0的数据],
sum(case when 分类 = 2 and 编码 = 1 then 1 else 0 end) [分类2编码1的数据],
sum(case when 分类 = 3 and 编码 = 0 then 1 else 0 end) [分类3编码0的数据],
sum(case when 分类 = 3 and 编码 = 1 then 1 else 0 end) [分类3编码1的数据]
from [table]
group by 用户id
drop table [table]
/*
用户id 分类1编码0的数据 分类1编码1的数据 分类2编码0的数据 分类2编码1的数据 分类3编码0的数据 分类3编码1的数据
----------- ----------- ----------- ----------- ----------- ----------- -----------
1111 0 1 0 0 0 0
3333 1 0 1 0