gpt4 book ai didi

mysql - 数据库 SQL 查询按第一列对结果进行分组

转载 作者:行者123 更新时间:2023-11-29 17:12:34 27 4
gpt4 key购买 nike

我需要查询方面的帮助,我想按前两列对结果行进行分组,但我不知道如何继续。

我的查询

 SELECT student_number, homework_name, homework_points 
FROM student, homework
WHERE student.studentid = homework.studentid

下面是我的查询结果

student_number  homework_name  homework_points
-------------- ------------- ---------------
7554 Homework 1 22.5
7554 Homework 2 16.0
7677 Homework 1 36.0
7677 Homework 2 14.5

我将如何转换查询以获得这样的结果

student_number  Homework 1     Homework 2
-------------- ------------- ---------------
7554 22.5 16.0
7677 36.0 14.5

任何帮助将不胜感激。

谢谢!

最佳答案

SELECT s.student_number, 
sum(case when h.homework_name = 'Homework 1' then h.homework_points else 0 end) as Homework_1,
sum(case when h.homework_name = 'Homework 2' then h.homework_points else 0 end) as Homework_2
FROM student s
JOIN homework h ON s.studentid = h.studentid
GROUP BY s.student_number

关于mysql - 数据库 SQL 查询按第一列对结果进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51810454/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com