[英]aggregating multiple rows in SQL
例如,我有一張如下表 -
----------------------------------------------------------------------
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
現在,從這張表我想實現下表 -
----------------------------------------------------------------------
id | student_id | section_id | sunday_subj | monday_subj | friday_subj
----------------------------------------------------------------------
1 | U1 | 4 | math | biology | zoology
2 | U2 | 6 | biology | biology | math
----------------------------------------------------------------------
從您的問題中並不完全清楚您如何定義組,但這是一個猜測:
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。
選擇列表的所有其他列都必須在聚合函數內。
您可以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
看演示
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.