在SQL中聚合多行

时间:2019-01-18 17:34:39

标签: mysql sql group-by

例如,我有一个如下表-

mvn flyway:validate -Dflyway.configFile=myFlywayConfig.properties

现在,我要从此表中获得下表-

----------------------------------------------------------------------
id | student_id | section_id | sunday_subj | monday_subj | friday_subj
----------------------------------------------------------------------
1 |      U1     |     4      |    math     |             |            
2 |      U1     |     4      |             |   biology   |            
3 |      U1     |     4      |             |             |  zoology    
4 |      U2     |     6      |   biology   |             |            
5 |      U2     |     6      |             |   zoology   |            
6 |      U2     |     6      |             |             |    math

2 个答案:

答案 0 :(得分:0)

从您的问题中尚不清楚您是如何定义组的,但这是一个猜测:

SELECT MIN(id) id,
       student_id,
       section_id,
       MAX(sunday_subj) sunday_subj,
       MAX(monday_subj) monday_subj,
       MAX(friday_subj) friday_subj
FROM MyTable
GROUP BY student_id, section_id;

这至少说明您可以在两列上使用GROUP BY。

选择列表的所有其他列必须在聚合函数内。

答案 1 :(得分:0)

您可以group by student_id, section_id

set @i = 0;
select 
  (select @i:=@i+1) id, 
  t.student_id, 
  t.section_id, 
  max(sunday_subj) sunday_subj,
  max(monday_subj) monday_subj,
  max(friday_subj) friday_subj
from tablename t
group by t.student_id, t.section_id

请参见demo