SQL中的行转列面试题

要求只用一个select,拿到英语和数学成绩60分以上、且化学和历史80分以上的每个人姓名,表数据如下:

usernamesubjectperformance
英语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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值