返回array_agg()中的第一个元素

时间:2015-06-23 08:06:13

标签: sql postgresql

我正在写一个查询,以获得所有球队的所有球员。我决定使用array_agg()在单个查询中获取所有团队的玩家,而不是在应用程序中循环。我写了如下查询:

SELECT team_id, array_agg(team_name) AS teamname,
       array_agg(player_id||'##'||player_name) AS playerdetails
FROM team
INNER JOIN players ON team_id = player_team
GROUP BY team_id

此查询给出了如下结果,在结果集中重复了teamname(确切地说是玩家的数量)

team_id             team_name                                                                   playerdetails
1       {Australia,Australia,Australia,Australia}                       {"5##Glenn Donald McGrath","6##Shane Warne","2##Steve Waugh","1##Adam Gilchrist"}
2       {India,India,India,India}                                       {"8##Kapil Dev","11##Saurav Ganguly","3##Rahul Dravid","9##Sachin Tendulkar"}
3       {"South Africa","South Africa","South Africa","South Africa"}   {"12##Gary Kristen","4##Shaun Pollock","7##Jacques Kallis","10##Alan Donald"}

有没有办法像这样返回结果

team_id             team_name                                                                   playerdetails
1                   Australia                       {"5##Glenn Donald McGrath","6##Shane Warne","2##Steve Waugh","1##Adam Gilchrist"}

我使用子查询实现了它,但想知道是否可以在没有子查询的情况下编写它

SELECT team_id, teamname[1], playerdetails
FROM (
  SELECT team_id, array_agg(team_name) AS teamname,
         array_agg(player_id||'##'||player_name) AS playerdetails
  FROM team
  INNER JOIN players ON team_id = player_team
  GROUP BY team_id) AS tempresult  

sqfiddle就在这里。我正在使用Postgresql 8.4

[编辑]
当我尝试检索未在组中指定的列时,我实际上想到了GROUP BY限制column "team.team_status" must appear in the GROUP BY clause or be used in an aggregate function的攻击

SELECT team_id, array_agg(team_name) AS teamname,
       array_agg(player_id||'##'||player_name) AS playerdetails,
       team_status -- could be replaced by something like array_agg(team_status)[0] or customfunction(team_status)
FROM team
INNER JOIN players ON team_id = player_team
GROUP BY team_id   

3 个答案:

答案 0 :(得分:4)

很简单,不要聚合team_name而是GROUP BY它:

SELECT team_id, team_name, array_agg(player_id||'##'||player_name) AS playerdetails
FROM team
JOIN players ON team_id = player_team
GROUP BY team_id, team_name;

答案 1 :(得分:4)

这实际上是我的错误......我的第一个问题的答案在于查询本身。我只需要附上(array_agg(team_name))[1],之前我没有括号就试过了。

SELECT team_id, (array_agg(team_name))[1] AS teamname,
     array_agg(player_id||'##'||player_name) AS playerdetails
FROM team
INNER JOIN players ON team_id = player_team
GROUP BY team_id

答案 2 :(得分:0)

SELECT team_id,array_agg( distinct team_name)AS团队名称, array_agg(player_id ||'##'|| player_name)AS玩家详细信息 来自团队 INNER JOIN玩家进入team_id = player_team GROUP BY team_id