首页 新闻 会员 周边

SQL语句请教

0
悬赏园豆:5 [已关闭问题] 关闭于 2010-01-11 16:53

有一个表数据如下:

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语句怎么写呢

yuejianjun的主页 yuejianjun | 初学一级 | 园豆:20
提问于:2009-12-29 19:16
< >
分享
所有回答(3)
0

代码
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

 

清海扬波 | 园豆:825 (小虾三级) | 2009-12-29 19:48
你这种不行吧 我真实情况会有很多数据的 再是我只要SQL语句,不能要存储过程
支持(0) 反对(0) yuejianjun | 园豆:20 (初学一级) | 2009-12-30 09:43
0

既然有很多列,横向输出就有问题,

cid1    2  

cid2   1      

cid3   2 

select cid  ,sum(cid)  from table

group by cid

 

哈哈

OOLi | 园豆:163 (初学一级) | 2009-12-30 13:59
0
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

JasonXu | 园豆:195 (初学一级) | 2009-12-30 14:09
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册