日期:2014-05-18  浏览次数:20707 次

一个分类汇总的查询语句

姓名 类型
小王 A
小王 C
小红 B
李四 A
张三 C
小王 C
小王 B
小王 C
小红 C 
李四 C
  

要求结果
姓名 A B C
小王 1 1 3
小红 0 1 1
李四 1 0 1
张三 0 0 1

select 姓名,SUM(类型) as 'A',sum(类型) as 'B',SUM(类型) AS 'C' 
from 表 where 类型='A'OR 类型='B' OR 类型='C' 
group by 姓名

我这样写但查出来的不是我想要的 ,求解答。。本人初学者,说的详细点 谢谢

------解决方案--------------------
SQL code

select 姓名,SUM((case when 类型='A' then 1 else 0 end)) as 'A',
            SUM((case when 类型='B' then 1 else 0 end)) as 'B',  
            SUM((case when 类型='C' then 1 else 0 end)) as 'C'
from 表 
group by 姓名

------解决方案--------------------
SQL code
select 姓名,
       sum(case when 类型='A' then 1 else 0 end) A,
       sum(case when 类型='A' then 1 else 0 end) B,
       sum(case when 类型='A' then 1 else 0 end) C
from tb
group by 姓名