有一个表数据如下:
id cid
1 1
2 3
3 1
4 3
5 2
我想输出:3个字段的值,它们分别是cid=1,cid=2,cid=3 的个数
例如该处输出为:
cid1 cid2 cid3
2 1 2
这个SQL语句怎么写呢
declare @t table(id int, cid int)
insert @t
select 1, 1
union all
select 2, 3
union all
select 3, 1
union all
select 4, 3
union all
select 5, 2
select sum(case cid when 1 then 1 else 0 end)as cid1,
sum(case cid when 2 then 1 else 0 end)as cid2,
sum(case cid when 3 then 1 else 0 end)as cid3
from @t
既然有很多列,横向输出就有问题,
cid1 2
cid2 1
cid3 2
select cid ,sum(cid) from table
group by cid
哈哈
1 SELECT [1] AS b1, [2] AS b2, [3] AS b3, [5] AS b5
2 FROM
3 ( SELECT b
4 FROM tab) p
5 PIVOT
6 (
7 COUNT (b)
8 FOR b IN
9 ( [1], [2], [3], [5] )
10 ) AS pvt
a b
1 | 1 |
2 | 2 |
3 | 3 |
4 | 5 |
5 | 3 |
6 | 2 |
7 | 5 |
8 | 5 |
9 | 1 |
10 | 3 |
11 | 3 |
结果:
b1 b2 b3 b5
2 2 4 3