一道SQL语句面试题,关于group by
表内容:
2015-05-09 胜
2015-05-09 胜
2015-05-09 负
2015-05-09 负
2015-05-10 胜
2015-05-10 负
2015-05-10 负
如果要生成下列结果, 该如何写sql语句?
胜 负
2015-05-09 2 2
表内容:
2015-05-09 胜
2015-05-09 胜
2015-05-09 负
2015-05-09 负
2015-05-10 胜
2015-05-10 负
2015-05-10 负
如果要生成下列结果, 该如何写sql语句?
胜 负
2015-05-09 2 2
2015-05-10 1 2
--创建表(表示建立一个临时表#tmp,在过程结束,会把该表释放掉,不会存储到数据库)
create table #tmp (
rq varchar(10),
shengfu nchar(1)
)
--插入数据
insert into #tmp values('2015-05-09','胜')
insert into #tmp values('2015-05-09','胜')
insert into #tmp values('2015-05-09','负')
insert into #tmp values('2015-05-09','负')
insert into #tmp values('2015-05-10','胜')
insert into #tmp values('2015-05-10','负')
insert into #tmp values('2015-05-10','负')
--查询表中数据
select * from #tmp
--查询需要得到的结果
select rq as ' ',SUM(case when shengfu='胜' then 1 else 0 end) '胜',SUM(case when shengfu='负' then 1 else 0 end) '负'
from #tmp
group by rq
或者(但不是很推荐这样写)
select rq ,SUM(case shengfu when '胜' then 1 else 0 end) '胜',SUM(case shengfu when '负' then 1 else 0 end) '负'
from #tmp
group by rq