按第一列的数据库SQL查询组结果

时间:2018-08-12 15:55:56

标签: mysql sql group-by pivot

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

我的查询

 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

任何帮助将不胜感激。

谢谢!

5 个答案:

答案 0 :(得分:0)

用例何时

        SELECT student_number, 
        max(case when homework_name='Homework 1' then homework_points end) as Homework1,
       max(case when homework_name='Homework 2' then homework_points end) as Homework2
        FROM student inner join homework 
       on student.studentid = homework.studentid 
      group by student_number

http://sqlfiddle.com/#!9/c33289/2

id    Homework1  Homework2
7554    22.5     16
7677    36       14

答案 1 :(得分:0)

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

答案 2 :(得分:0)

您可以使用几张表进行作业

   SELECT s.student_number
      , a.homework_points AS  `Homework 1`
      ,  b.homework_points AS  `Homework 21`
   FROM student s
   LEFT JOIN homework a ON s.studentid = a.studentid 
          and a.homework_name =' Homework 1' 
   left JOIN homework b ON s.studentid = b.studentid 
        and b.homework_name =' Homework 2'
    ORDER BY s.student_number

答案 3 :(得分:0)

首先,您确实应该使用适当的联接而不是where子句来进行联接:

SELECT student_number, homework_name, homework_points
FROM student join homework on student.studentid = homework.studentid

关于您的实际问题,请尝试以下操作:

select student_name,
h1.homework_points as homework_1,
h2.homework_points as homework_2
from student s
left join homework h1
  on s.studentid = h1.studentid and h1.homework_name = 'Homework 1'
left join homework h2
  on s.studentid = h2.studentid and h2.homework_name = 'Homework 2'
where h1.homework_id is not null or h2.homework_id is not null

请注意使用左联接的依据是特定学生可能只完成了两种作业中的一种。

答案 4 :(得分:0)

我认为其他答案是正确的。

但是,我觉得您不是在寻找硬编码的列列表。如果这是您想要的,那么您正在寻找“数据透视” SQL语句。

SQL Server(作为枢轴)或PostgreSQL(作为交叉表)中有一些实现,但是我还没有看到MySQL或MariaDB中的任何实现。