选择Groupby-Postgres v12中未提及所有列的多个列

问题描述 投票:0回答:3

我有一个表,其中包含review_id,product_id,评分,reviewer_id,review_comments。我的桌子如下。enter image description here

我的需求很简单,但是我很难解决。需要获得product_id的product_id,评分,reviewer_id和review_comments,其最大值为review_id

通过下面的查询,我能够正确获取product_id和review_id。

SELECT product_id,max(review_id) as review_id
    FROM public.products Group by product_id;

但是当我尝试添加评分,reviewer_id和review_comments时,会产生一个错误,即这些列必须是groupby的一部分,如果添加这些列,则由于我只需要对product_id进行分组,就没有其他分组了。

有没有办法解决这个问题?

我的预期结果应包含带有review_id 7、5、8的所有行内容,因为对于product_id 1,review_id 7最高,对于product_id 2,review_id 5最高,对于product_id 3,review_id 8最高。

sql postgresql greatest-n-per-group
3个回答
2
投票

尝试PostgreSQL的DISTINCT ON

SELECT DISTINCT ON (product_id)
       product_id,
       review_id,
       rating,
       reviewer_id,
       review_comments
FROM products
ORDER BY product_id, review_id DESC;

这将按product_id顺序返回每个ORDER BY的第一行。


1
投票

这可以通过NOT EXISTS完成:

select p.product_id, p.rating, p.reviewer_id, p.review_comments
from public.products p
where not exists (
  select 1 from public.products
  where product_id = p.product_id and review_id > p.review_id
)

0
投票

您可以尝试以下方式-

select * from tablename a
where review_id =(select max(review_id) from tablename b where a.product_id=b.product_id)

或使用row_number()

select * from
(
select *, row_number() over(partition by product_id order by review_id desc) as rn
from tablename
)A where rn=1
© www.soinside.com 2019 - 2024. All rights reserved.