代码改变世界

group by 面试题

2011-11-18 15:24  阿普的博客  阅读(515)  评论(0编辑  收藏  举报

 

数据库表table1

 日期            胜负

 2009-12-9     胜

2009-12-9     胜

2009-12-9     负

2009-12-9     负

2009-12-10    负

2009-12-10    胜

查询结果 日期          

 胜      负

2009-12-9    2   2

2009-12-10   1      1

写出sql语句:

 

select 日期,SUM(case 胜负 when '胜' then 1 end) 胜,SUM(case 胜负 when '负' then 1 end) 负
from table1
group by 日期

select 日期,(select COUNT(*) from table1 where 胜负='胜' and t.日期=日期) 胜
,(select COUNT(*) from table1 where 胜负='负' and t.日期=日期) 负
from table1 t
group by 日期

运行结果: