简体   繁体   English

postgres 分组

[英]postgres grouping

I am having a db names products where i wanted to select the price of each product based on the id, but the price that i stored in the table is from different sources.我有一个数据库名称产品,我想要 select 基于 id 的每个产品的价格,但我存储在表中的价格来自不同的来源。 So i want one latest price from each of the source.所以我想要每个来源的最新价格。 My table looks like this我的桌子看起来像这样

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

i want the output to be like this when my where condition is for id=3当我的 where 条件为 id=3 时,我希望 output 像这样

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

i tried running the我试着运行

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

but this one brings only one row irrespective of the source但是不管来源如何,这一个只带来一行

could any one help me out with this.谁能帮我解决这个问题。 I am extremely new to postgres and sql queries.我对 postgres 和 sql 查询非常陌生。 I would really appreciate your help.我将衷心感谢您的帮助。

Using DISTINCT ON :使用DISTINCT ON

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

It's not really clear what you want to do.目前还不清楚你想做什么。 If you would like to sum the price for the product with id 3 not having the text "..." in the column "updated_at", you can do this query:如果您想对 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;

See this example and try out: db<>fiddle Modify the query to your desires if necessary.请参阅此示例并尝试: db<>fiddle如有必要,请根据您的需要修改查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM