簡體   English   中英

PostgreSQL-GROUP BY條件,如果值在兩列之一中

[英]PostgreSQL - GROUP BY condition, if a value is in one of two columns

假設我有運動隊參加比賽。 游戲表具有以下字段:

home_idaway_id

其中home_id和away_id是與團隊相關的外鍵。

我想以某種方式進行一項操作(GROUP BY?),在該操作中,我可以獲取所有團隊的ID都在away_id列或home_id列中的所有游戲。

有沒有辦法做到這一點?

提前致謝!

您不需要GROUP BY即可實現。 該查詢很容易解釋:

SELECT * FROM games WHERE home_id = some_team_id OR away_id = some_team_id

如果我正確理解OP,他想要下面的矩陣。 他可以過濾的內容:

t=# with s(game,home,away) as (values(1,1,2),(2,2,1),(3,2,3),(4,3,2),(5,1,5))
, m as (select unnest(array[home,away]) ar,game from s)
select ar team,count(1),array_agg(game) games from m group by ar order by ar;
 team | count |   games
------+-------+-----------
    1 |     3 | {2,5,1}
    2 |     4 | {4,3,1,2}
    3 |     2 | {3,4}
    5 |     1 | {5}
(4 rows)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM