在另一列中具有公共值的列的SQL聚合

在另一列中具有公共值的列的SQL聚合,sql,postgresql,select,group-by,string-aggregation,Sql,Postgresql,Select,Group By,String Aggregation,对于我在PostgreSQL中提出的一个查询,我有一个尚未解决的疑问 我有这两张桌子 玩家 这就是我的疑问 SELECT DISTINCT concat(N.playerID, ':', N.title), TID FROM player N INNER JOIN ( SELECT DISTINCT P.playerID as PID, teamID as TID FROM plays P ) AS derivedTable ON N.playerID = PID ORDER BY

对于我在PostgreSQL中提出的一个查询,我有一个尚未解决的疑问

我有这两张桌子

玩家

这就是我的疑问

SELECT DISTINCT concat(N.playerID, ':', N.title), TID 
FROM player N
INNER JOIN (
 SELECT DISTINCT P.playerID  as PID,  teamID as TID
 FROM plays P
 ) AS derivedTable 
ON N.playerID = PID
ORDER BY concat
查询结果为:

"1:Rondo"  |  1 
"1:Rondo"  |  2
"1:Rondo"  |  3
"2:Allen"  |  1
"2:Allen"  |  3
"3:Pierce" |  1
"3:Pierce" |  3
但是我想要那样的东西

"1:Rondo"  |  1, 2, 3
"2:Allen"  |  1, 3
"3:Pierce" |  1, 3
我可以使用数组,但我真的不知道如何使用MySQL

试试这个:

SELECT CONCAT(N.playerID, ':', N.title) playerTitle, 
       GROUP_CONCAT(P.TID SEPARATOR ', ') TID
FROM player N 
LEFT JOIN plays P ON N.playerID = PID 
GROUP BY N.playerID
ORDER BY playerTitle
使用字符串_agg

您的派生表不是必需的,Postgres中更明显的是:

SELECT concat(N.playerID, ':', N.title) title, string_agg(P.TID,', ') TID
FROM player N 
LEFT JOIN plays P ON N.playerID = P.PID 
GROUP BY 1
ORDER BY 1

如果目标RDBMS是Postgresql,那么为什么还要使用其他标记呢?您需要一个透视表
SELECT CONCAT(N.playerID, ':', N.title) playerTitle, 
       GROUP_CONCAT(P.TID SEPARATOR ', ') TID
FROM player N 
LEFT JOIN plays P ON N.playerID = PID 
GROUP BY N.playerID
ORDER BY playerTitle
SELECT concat(N.playerID, ':', N.title), 
       string_agg(p.TeamID::text, ',') as teamid_list
FROM player N
  JOIN plays p ON n.playerID = p.playerID
GROUP BY n.playerID, n.title
ORDER BY 1;
SELECT concat(N.playerID, ':', N.title) title, string_agg(P.TID,', ') TID
FROM player N 
LEFT JOIN plays P ON N.playerID = P.PID 
GROUP BY 1
ORDER BY 1