簡體   English   中英

postgres 分組

[英]postgres grouping

我有一個數據庫名稱產品,我想要 select 基於 id 的每個產品的價格,但我存儲在表中的價格來自不同的來源。 所以我想要每個來源的最新價格。 我的桌子看起來像這樣

id | name | source | updated_at | price 
1  | ace  | vanil  | ...        | 100
2  | vax  | vanil  | ...        | 101
3  | tax  | sunyil | ...        | 200
1  | ace  | sunyil | latest     | 99.5
2  | vax  | sunyil | latest     | 100.5
3  | tax  | vanil  | latest     | 199.5
3  | tax  | vanil  | ...        | 220
3  | tax  | vanil  | ...        | 211
3  | tax  | vanil  | ...        | 205
3  | tax  | sunyil | ...        | 211
3  | tax  | vanil  | ...        | 220
3  | tax  | sunyil |latest_time | 220
1  | ace  | sunyil | ...        | 101

當我的 where 條件為 id=3 時,我希望 output 像這樣

id | name | source | updated_at | price
 3 | tax  | vanil  | latest time| 199.5
 3 | tax  | sunyil | latest time| 220

我試着運行

select * from products WHERE id= '3' ORDER BY updated_at DESC LIMIT 1 

但是不管來源如何,這一個只帶來一行

誰能幫我解決這個問題。 我對 postgres 和 sql 查詢非常陌生。 我將衷心感謝您的幫助。

使用DISTINCT ON

SELECT DISTINCT ON (id, source) *
FROM products
WHERE id = 3
ORDER BY id, source, updated_at DESC;

目前還不清楚你想做什么。 如果您想對 ID 為 3 且在“updated_at”列中沒有文本“...”的產品的價格求和,您可以執行以下查詢:

SELECT id, name, source, updated_at, SUM(price) FROM products 
WHERE id = 3 and updated_at != '...'
GROUP BY id, name, source, updated_at ORDER BY updated_at;

請參閱此示例並嘗試: db<>fiddle如有必要,請根據您的需要修改查詢。

暫無
暫無

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

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