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

时间:2014-12-16 13:59:57

标签: sql postgresql select group-by string-aggregation

我对PostgreSQL中的查询有一个未解决的疑问。

我有这两个表

PLAYER

playerID      title
1             Rondo
2             Allen
3             Pierce
4             Garnett
5             Perkins<

PLAYS

playerID      TeamID
   1             1
   1             2
   1             3
   2             1
   2             3
   3             1
   3             3

那是我的查询

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

我可以使用array_agg,但我真的不知道如何

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

使用string_agg()

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;

您的派生表不是必需的(而且更加明显)

答案 2 :(得分:0)

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