mysql笔试题

http://blog.csdn.net/gladyoucame/article/details/8560053 笔试1

 

1.一道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-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

 

2.表中有A B C三列,用SQL语句实现:当A列大于B列时选择A列否则选择B列,当B列大于C列时选择B列否则选择C列。
------------------------------------------
select (case when a>b then a else b end ),
(case when b>c then b esle c end)
from table_name

 

drop table table1
create table table1(
a int,
b int,
c int
)
insert into table1 values(22,24,23)

select * from table1

select (case when a>b then a else b end),(case when b>c then b else c end)
from table1

select (case when a>b then a
when a>c then a
when b>c then b else c
end)
from table1

 

posted on 2016-03-10 16:51  阿卡贝拉  阅读(182)  评论(0)    收藏  举报