简体   繁体   中英

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.

All the other columns of your select-list must be inside aggregate functions.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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