SQL查询结果行转列问题

2 篇文章 0 订阅

1.数据准备

select * from student;

select * from score;

2.要求:查询出有成绩学生的各科成绩信息和总分,并按照总分降序排列,显示效果如下

①关联自身表查询

SELECT
    a. NAME '姓名',
    b.score '语文',
    c.score '数学',
    d.score '英语',
    (b.score + c.score + d.score) '总分'
FROM
    student a
JOIN score b ON a.id = b.uid
JOIN score c ON a.id = c.uid
JOIN score d ON a.id = d.uid
WHERE
    b. SUBJECT = '语文'
AND c. SUBJECT = '数学'
AND d. SUBJECT = '英语'
ORDER BY
    (b.score + c.score + d.score) DESC;

②使用case关键字优化查询

select a.`name`,
sum(case when subject='语文' then b.score end) as '语文',
sum(case when subject='数学' then b.score end) as '数学',
sum(case when subject='英语' then b.score end) as '英语',
sum(b.score) as '总分'
from student a
join score b on a.id = b.uid
GROUP BY a.name
order by sum(b.score) desc;

3.总结

在数据量相对较大的情况,推荐使用case关键字优化查询,避免多次关联自身表查询。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值