简体   繁体   English

在 SQL 中聚合多行

[英]aggregating multiple rows in SQL

For example, I have a table like below -例如,我有一张如下表 -

----------------------------------------------------------------------
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

Now, from this table I want to achieve the following table -现在,从这张表我想实现下表 -

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

It's not totally clear from your question how you are defining the groups, but here's a guess:从您的问题中并不完全清楚您如何定义组,但这是一个猜测:

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;

This at least demonstrates that you can use GROUP BY on two columns.这至少表明您可以在两列上使用 GROUP BY。

All the other columns of your select-list must be inside aggregate functions.选择列表的所有其他列都必须在聚合函数内。

You can group by student_id, section_id您可以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

See the demo演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM