首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

这个GROUP BY 要如何写

2013-06-19 
这个GROUP BY要怎么写?table1:nameLB1fld1fld2张三A李四B张三A李四B张三B李四A王五A要求结果:nameAB张三21

这个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

热点排行