簡體   English   中英

按聚合選擇組上的整行

[英]Select entire row on group by aggregation

我對應該是一個簡單的 SQL 查詢的東西有些掙扎。

這是我的初始數據庫架構:

![初始數據庫模式

還准備了SQLFiddle中的例子

我最終得到的查詢是:

select
       b.ad_id,
       b.auction_id,
       max(b.amount) as max,
       max(b.created_at) created_at
from bid b
where b.user_id = '601'
group by b.ad_id, b.auction_id

但在結果中,我需要bid表中的整行:

select
       b.id,
       b.ad_id,
       b.auction_id,
       max(b.amount) as max,
       max(b.created_at) created_at
from bid b
where b.user_id = '601'
group by b.ad_id, b.auction_id

失敗: [42803] ERROR: column "b.id" must appear in the GROUP BY clause or be used in an aggregate function Position: 16 無法在 GROUP BY 子句中添加id字段,因為它會添加一些我不需要的額外行。

我需要的是從bid表中選擇按auction_id 和ad_id 分組的最高記錄(金額字段)。

我想我需要進行一些自我內部連接或子選擇,但現在我無法編寫 SQL。

我需要的是從出價表中選擇按auction_id 和ad_id 分組的最高記錄(金額字段)

看看文檔中的DISTINCT ON 您想要的結果將通過以下查詢獲得。

select DISTINCT ON (b.ad_id, b.auction_id)
       b.id,
       b.ad_id,
       b.auction_id,
       b.amount
       b.created_at
from bid b
where b.user_id = '601'
ORDER BY b.ad_id, b.auction_id, b.amount DESC

如果您想要給定用戶的每次拍賣的最新行,那么您可以使用相關子查詢來過濾:

select b.*
from bid b
where b.user_id = '601' and
      b.created_at = (select max(b2.created_at)
                      from bid b2
                      where b2.auction_id = b.auction_id and
                            b2.user_id = b.user_id
                     );

這似乎是對您想要的東西的明智解釋。 我不知道是否需要ad_id

暫無
暫無

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

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