如何分类综合统计
现有一表tableA ( Pid ,Pdate,Pname,PSum,Pmemo)
表内容:
1, 2013-10-1, 张三,9,no
2, 2013-10-1, 李四,19,no
3, 2013-10-1, 王二麻,8,no
4, 2013-10-1, 张三,38,no
5, 2013-10-1, 李四,11,no
6, 2013-10-1, 王二麻,2,no
7, 2013-10-1, 李四,15,no
要求按pName 进行统计
名称 ,PSum小于10次数,PSum大于20次数,PSum大于10并且小于20次数
张三 0 0 0
李四
王二麻
怎么样统计呢?
[解决办法]
--> 测试数据:tableA
if object_id('tableA ') is not null drop table tableA
go
create table tableA ([Pid] int,[Pdate] datetime,Pname varchar(10),PSum int)
insert tableA
select 1,'2013-10-1','张三',9 union all
select 2,'2013-10-1','李四',19 union all
select 3,'2013-10-1','王二麻',8 union all
select 4,'2013-10-1','张三',38 union all
select 5,'2013-10-1','李四',11 union all
select 6,'2013-10-1','王二麻',2 union all
select 7,'2013-10-1','李四',15
select pname,[PSum小于10]=sum(case when psum <10 then 1 else 0 end ),
[PSum10-20]=sum(case when psum >=10 and psum <20 then 1 else 0 end ),
[PSum大于20]=sum(case when psum >20 then 1 else 0 end )
from tableA
group by pname
if object_id('tableA ') is not null drop table tableA
go
create table tableA ([Pid] int,[Pdate] datetime,Pname varchar(10),PSum int)
insert tableA
select 1,'2013-10-1','张三',9 union all
select 2,'2013-10-1','李四',19 union all
select 3,'2013-10-1','王二麻',8 union all
select 4,'2013-10-1','张三',38 union all
select 5,'2013-10-1','李四',11 union all
select 6,'2013-10-1','王二麻',2 union all
select 7,'2013-10-1','李四',15
go
select Pname,
count(case when PSum<10 then 1 else null end) as [PSum小于10次数],
count(case when PSum>20 then 1 else null end) as [PSum大于20次数],
count(case when PSum>=10 and PSum < 20 then 1 else null end) as [PSum大于10并且小于20次数]
from tableA
group by Pname
/*
PnamePSum小于10次数PSum大于20次数PSum大于10并且小于20次数
李四003
王二麻200
张三110
*/