日期:2014-05-17  浏览次数:20433 次

这个GROUP BY 要怎么写?
table1:

name  LB1  fld1   fld2
张三    A
李四     B
张三     A
李四     B
张三     B
李四     A
王五     A

要求结果:

name   A   B
张三    2   1
李四    1   2
王五    1   0

fld1  fld2 可以加在where 条件中。

------解决方案--------------------
select name,
sum((case lb when 'A' then 1 else 0 end)) A,
sum((case lb when 'B' then 1 else 0 end)) B
from cc group by name order by name desc
------解决方案--------------------

select name,
sum((case LB1 when 'A' then 1 else 0 end)) A,
sum((case LB1 when 'B' then 1 else 0 end)) B
from table1 group by name

------解决方案--------------------

select tname,A=(select count(1) from table1 where a.tname=tname and sex='a'),
B=(select count(1) from table1 where a.tname=tname and sex='b') from table1  a