Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在SQL中聚合多行_Mysql_Sql_Group By - Fatal编程技术网

Mysql 在SQL中聚合多行

Mysql 在SQL中聚合多行,mysql,sql,group-by,Mysql,Sql,Group By,例如,我有一个如下表- ---------------------------------------------------------------------- id | student_id | section_id | sunday_subj | monday_subj | friday_subj ---------------------------------------------------------------------- 1 | U1 | 4

例如,我有一个如下表-

----------------------------------------------------------------------
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;
这至少表明您可以在两列上使用GROUPBY


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

您可以
按学生id分组,部分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

请参见

注意,数据库表不是电子表格。见正常化!而且,结果集中的id是没有意义的