Typeor order by after distinct on with postgresql
Typeorm order by after distinct on with postgresql
我下面有一个table:
id
product_id
price
1
1
100
2
1
150
3
2
120
4
2
190
5
3
100
6
3
80
我想select产品的最低价格并按价格排序
预期输出:
id
product_id
price
6
3
80
1
1
100
3
2
120
到目前为止我尝试了什么:
`
repository.createQueryBuilder('products')
.orderBy('products.id')
.distinctOn(['products.id'])
.addOrderBy('price')
`
此查询 returns,最便宜的产品但未对它们进行排序。所以,addOrderBy
对产品没有影响。有没有办法在 distinctOn
之后对产品进行排序?
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)
我下面有一个table:
id | product_id | price |
---|---|---|
1 | 1 | 100 |
2 | 1 | 150 |
3 | 2 | 120 |
4 | 2 | 190 |
5 | 3 | 100 |
6 | 3 | 80 |
我想select产品的最低价格并按价格排序
预期输出:
id | product_id | price |
---|---|---|
6 | 3 | 80 |
1 | 1 | 100 |
3 | 2 | 120 |
到目前为止我尝试了什么:
`
repository.createQueryBuilder('products')
.orderBy('products.id')
.distinctOn(['products.id'])
.addOrderBy('price')
`
此查询 returns,最便宜的产品但未对它们进行排序。所以,addOrderBy
对产品没有影响。有没有办法在 distinctOn
之后对产品进行排序?
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)