SQL-按特定字段分组,并合并另一个字段

时间:2018-12-13 14:23:49

标签: mysql sql group-by grouping concat

我有一个返回下表的查询:

   P_id   S_id   Time
1  "20"     A    15 
2  "30"     B    50
3  "50"     A    99 
4  "70"     A    60

我想基于“ Sid”列对表进行分组,并按“时间”列进行排序,因此它看起来像这样:

        P_id       S_id   
1  "20","70","50"    A     
2       "30"         B    

通过更改SQL查询来做到这一点的最佳方法是什么?

尝试仅添加“ GROUP BY S_id”时,出现错误:

SELECT list expression references column query which is neither grouped nor aggregated at [2:16]

(意味着它不知道如何对P_id(所有字符串)的值进行分组

2 个答案:

答案 0 :(得分:1)

我想你想要

checkedListBox1.SelectedValueChanged -= checkedListBox1_SelectedValueChanged;
checkedListBox1.DataSource = cboxAr;
checkedListBox1.SelectedValueChanged += checkedListBox1_SelectedValueChanged;

如果您希望第一列包含数字,则可以将其添加到:

select s_id, group_concat(p_id order by time) as p_ids
from t
group by s_id;

答案 1 :(得分:0)

select group_concat(P_id,',') from tablename group by S_id ;