要求只用一个select,拿到英语和数学成绩60分以上、且化学和历史80分以上的每个人姓名,表数据如下:
username | subject | performance |
---|---|---|
甲 | 英语 | 98 |
乙 | 英语 | 95 |
丙 | 英语 | 84 |
丁 | 英语 | 56 |
甲 | 数学 | 40 |
乙 | 数学 | 64 |
丙 | 教学 | 73 |
丁 | 数学 | 85 |
乙 | 语文 | 72 |
丙 | 语文 | 92 |
丁 | 语义 | 64 |
甲 | 历史 | 95 |
乙 | 历史 | 81 |
丁 | 历史 | 76 |
甲 | 心学 | 86 |
乙 | 化学 | 81 |
查询SQL
with tmp as (
select * from (
values
('甲', '英语', 98),
('乙', '英语', 95),
('丙', '英语', 84),
('丁', '英语', 56),
('甲', '数学', 40),
('乙', '数学', 64),
('丙', '数学', 73),
('丁', '数学', 85),
('甲', '语文', 72),
('乙', '语文', 92),
('丙', '语文', 64),
('丁', '语文', 95),
('甲', '历史', 95),
('乙', '历史', 81),
('丙', '历史', 76),
('丁', '历史', 54),
('甲', '化学', 86),
('乙', '化学', 81),
('丙', '化学', 76),
('丁', '化学', 54)
) as t(username, subject, performance)
)
select
username
, sum(case when subject = '语文' then performance else null end) as yw
, sum(case when subject = '数学' then performance else null end) as sx
, sum(case when subject = '历史' then performance else null end) as ls
, sum(case when subject = '化学' then performance else null end) as hx
from tmp
group by username
having sum(case when subject = '语文' then performance else null end) > 60
and sum(case when subject = '数学' then performance else null end) > 60
and sum(case when subject = '历史' then performance else null end) > 80
and sum(case when subject = '化学' then performance else null end) > 80