选择多个列,而不是Groupby-Postgres v12中提到的所有列

我有一张表,其中包含review_id,product_id,评分,reviewer_id,review_comments。我的桌子如下。

选择多个列,而不是Groupby-Postgres v12中提到的所有列

我的需求很简单,但是我很难解决。需要获得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最高。

iseehr 回答:选择多个列,而不是Groupby-Postgres v12中提到的所有列

尝试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的第一行。

,

这可以通过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
)
,

您可以尝试以下方式-

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
本文链接:https://www.f2er.com/2908604.html

大家都在问