0

我有一张桌子:

价格 日期 product_id
1000 20:00 1
3000 23:00 2
5000 21:00 2
2000 19:00 1

如何按日期product_id排序,其中product_id是主要排序?所以它最终看起来像:

价格 日期 product_id
2000 19:00 1
1000 20:00 1
5000 21:00 2
3000 23:00 2

我试过了

SELECT * FROM prices ORDER BY date, product_id
SELECT * FROM (
 SELECT * FROM prices
 ORDER BY product_id
) AS p ORDER BY date

但这并没有返回我想要的

4

1 回答 1

2

因此,您希望按产品排序,但要基于产品的最早日期。

令人高兴的是,您可以在以下位置使用窗口函数order by

select p.*
from prices p
order by min(date) over (partition by product),
         product,
         date;

order by键执行以下操作:

  1. 计算产品的最短日期并将其用作第一个整体排序键。
  2. 按产品订购,因此如果在最短日期有联系,则产品将分开。
  3. 按每个产品内的日期订购
于 2021-01-14T21:37:34.983 回答