这样的sql语句怎么写...
表1:
[cust_id] [cust_grade]
1 1
2 1
3 1
4 1
5 3
6 5
效果
[sum1] [sum2] [sum3] [sum4] [sum5]
4 0 1 0 1
我想用case来做.
select 1sum=sum(case when cust_grade=1 then 1 else 0 end),
2sum=sum(case when cust_grade=2 then 1 else 0 end),
3sum=sum(case when cust_grade=3 then 1 else 0 end),
4sum=sum(case when cust_grade=4 then 1 else 0 end),
5sum=sum(case when cust_grade=5 then 1 else 0 end)
from customer
大概是这个意思...
但是错了 - -
正确的写法该是什么呢?
用case when...
------解决方案--------------------select [1sum]=sum(case when cust_grade=1 then 1 else 0 end),
[2sum]=sum(case when cust_grade=2 then 1 else 0 end),
[3sum]=sum(case when cust_grade=3 then 1 else 0 end),
[4sum]=sum(case when cust_grade=4 then 1 else 0 end),
[5sum]=sum(case when cust_grade=5 then 1 else 0 end)
from customer