SQL - 按特定字段分组并连接另一个字段

SQL - Group by certain field and concat another

我有一个查询 return 以下 table:

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

我想根据第 "Sid" 列对 table 进行分组,并按 "Time" 列排序,因此它看起来像这样:

        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 的值进行分组(所有字符串)

我想你想要:

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

如果您想要第一列有数字,您可以将其添加到:

select (@rn := @rn + 1) as seqnum, s_id, group_concat(p_id order by time) as p_ids
from t cross join
     (select @rn := 0) params
group by s_id;
select group_concat(P_id,',') from tablename group by S_id ;