0

我有一个下表:

ID product_id 价格 
1 1 100
2 1 150
3 2 120
4 2 190
5 3 100
6 3 80

我想为产品选择最便宜的价格并按价格排序

预期输出:

ID product_id 价格
6 3 80
1 1 100
3 2 120

到目前为止我尝试了什么:

`
 repository.createQueryBuilder('products')
.orderBy('products.id')
.distinctOn(['products.id'])
.addOrderBy('price')
`

此查询返回最便宜的产品,但不对它们进行排序。所以,addOrderBy对产品没有影响。有没有办法对产品进行分类distinctOn

4

1 回答 1

1
SELECT id,
       product_id,
       price
FROM   (SELECT id,
               product_id,
               price,
               Dense_rank()
                 OVER (
                   partition BY product_id
                   ORDER BY price ASC) dr
        FROM   product) inline_view
WHERE  dr = 1
ORDER  BY price ASC; 

设置:

postgres=# create table product(id int, product_id int, price int);
CREATE TABLE
postgres=# inseert into values (1,1,100),(2,1,150),(3,2,120),(4,2,190),(5,3,100),(6,3,80);
INSERT 0 6

输出

id | product_id | price
----+------------+-------
  6 |          3 |    80
  1 |          1 |   100
  3 |          2 |   120
(3 rows)
于 2022-01-30T09:00:23.967 回答