[英]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.