mysql 查询语句

2020-09-22  本文已影响0人  苍老师的眼泪

设想一个情景,有一个家庭,他们每个成员都需要买一种商业保险,每个人需要付的保险费是和本人的年龄相关的,那么怎么计算这个家庭需要支付的总费用是多少呢?
表:

id  name    age homeno
1   Edison  25   1
2   Mother  49   1
3   Father  51   1
4   Brother 31   1
5   Sister  NULL 1

sql:

select sum(case
when age < 20 then 0
when age >=20 and age < 30 then 200
when age >=30 and age < 40 then 300
when age >=40 and age < 50 then 400
when age is null then 0
else 100 end) as total from test group by homeno;

设想一个情景,有个学校想要招分数高的人,但是被招聘的群体分文理科,type = 0表示文科,type = 1表示理科。现在要对这个招聘群体排名:
表:

1   桂华   1   null   44
2   祝玉英 1   null    75
3   舒桂英 0   12     null
4   晏建军 0   84     null
5   谭亮   1   null   30
6   隋敏   1   null   69
7   刘振国 1   null    97
8   娄超   1   null   71
9   庞玉梅 1   null    21
10  楚秀芳 0   79     null
11  瞿英   1   null   38
12  霍小红 0   18     null
13  薄文娟 0   17     null
14  路华   1   null   100
15  万慧   0   48     null
16  银瑜   1   null   77

sql:

解决方案1:if
select * from test order by if(type = 0, liberal, science) desc;
解决方案2:case ... when ... then ... else ... end
select * from test order by case when type = 0 then liberal when type = 1 then science end desc;
select * from test order by case when type = 0 then liberal when type = 1 then science else liberal end desc;

设想有一个情景,你拿到一张某个年级的所有班的学生的成绩表,现在要求出每个班成绩最高的人的信息:
表:

id  name  class  score
32  花利   1      46
76  潘正业 1      46
86  臧博   1      22
41  潘建明 2      21
68  白捷   2      54
99  熊彬   2      11
72  宗松   3      88
78  路秀珍 3      35
81  查丽娟 3      90
22  姬洁   4      87
65  沙丽娟 4      71
95  邵静   4      72

sql:

方案1:left join
select i1.*, i0.* from info as i1 left join info as i0 
on i1.class = i0.class and i1.score < i0.score where i0.score is null 
order by i1.class, i1.id;

方案2: 子查询
select i1.* from info as i1 inner join 
    (select class, max(score) as max_score from info group by class) as i0 
    on i1.class = i0.class and i1.score = i0.max_score 
order by i1.class, i1.id;
上一篇下一篇

猜你喜欢

热点阅读