SQLServer 2008R2 用pivot 实现行专列

先说下需求,在客户表中有字段是个数据字典,表示客户分类,在表单中显示的是下拉框,现在需要一个报表,查看每个分类下有多少客户

1,表结构如下 create table Test_Acc (name nvarchar(50), type nvarchar(2) )

现在需要出表1表2两种维度的报表,

2.先插入模拟数据

insert test_acc values ('客户2','A')

insert test_acc values ('客户3','A')

insert test_acc values ('客户4','B')

insert test_acc values ('客户5','B')

insert test_acc values ('客户6','C')

insert test_acc values ('客户7','D')
insert test_acc values ('客户8','A')
insert test_acc values ('客户9','A')

insert test_acc values ('客户10','A')
insert test_acc values ('客户11','A')
insert test_acc values ('客户12','C')
insert test_acc values ('客户13','C')

3.表1的统计比较简单,一个Group by type 就能统计出来

select type ,count(*) from Test_Acc group by type

4.表2的统计需要进行行专列,我们用pivot的方式 

select * from (
select type ,count(*) as type_Count from Test_Acc group by type
) as t
pivot (sum(t.type_Count) for t.type in (A,B,C,D))as c

5.总结 pivot相对case when方式来进行转列省去了很多代码,性能也比较高

原文地址:https://www.cnblogs.com/hellohongfu/p/2705146.html