sql 分组统计 面试题
两道sql面试题,那人把试卷给我后居然坐在对面盯着看,我承认我受不了这个,愣死没答出来。他很鄙视我面向对象的四大特性只听说过三个,汗~~~
回来后几分钟搞定,不一定是最好的,但能应付笔试题。
1.表test结构:
group score
a 胜
b 负
a 负
b 胜
检索结果:
组 胜 负
a 1 1
b 1 1
sql:
select group as '组',count(case when score='胜' then score end) as '胜'
,count(case when score='负' then score else null end ) as '负'
from test group by group
,count(case when score='负' then score else null end ) as '负'
from test group by group
2.
表a结构
aid aname
1 a
2 b
表b结构
bid aid bname
1 1 111111
2 2 222222
3 1 333333
检索结果
aid aname bcount
1 a 2
2 b 1
sql
select aid,aname,(select count(0) from b where a.aid=b.aid) as bcount from a