1. 表内容:(table: date, result)
2005-05-09 | 胜 |
2005-05-09 | 胜 |
2005-05-09 | 负 |
2005-05-09 | 负 |
2005-05-10 | 胜 |
2005-05-10 | 负 |
2005-05-10 | 负 |
如果要生成下列结果,该如何写SQL?
胜 | 负 | |
2005-05-09 | 2 | 2 |
2005-05-10 | 1 | 2 |
解答:
# 将一维表调整为二维表
select date, sum(result="胜") as "胜",sum(result = "负") as "负"
from table
group by date;
2. 表中有A B C 三列数据,用SQL语句实现:当A列大于B列时选A列,否则选B列,当B列大于C列时选B列,否则选C列
# case when语句
select A, B, C,
case when A>B then A else B end,
case when B>C then B else C end
from table;
#直接使用if语句
select A,B,C, if(A>B,A,B), if(B>C,B,C)
from table;
3. A表的结构为em_id, em_name, em_tel, B表结构为 em_id, em_time(上班时间),请找出迟到(9:15)的员工编号,姓名,迟到次数
# 日期之间可以直接进行加减运算,可以直接与9:15进行对比,进行条件计数
select A.em_id, A.em_name, sum(em_time>"9:15:00") as "迟到次数"
from A
join B on A.em_id = B.em_id
group by A.em_id
4. 用一条SQL语句,查询每门课程都大于80分的学生姓名 (sc: st_name, kecheng, fenshu)
select st_name
from sc
group by st_name
having min(fenshu)>80
5. 有表:emp(id, em_name, age),要求:列出所有名字重复的人的记录。
select *
from emp
where em_name in (
select name
from emp
group by em_name
having count(*) >1)