最大值和最小值的时间戳

时间:2019-01-29 13:43:50

标签: postgresql

我有一张下表:

   id    | product_id | price |         timestamp          
---------+------------+-------+----------------------------
 1263479 |          1 |  1100 | 2019-01-21 21:08:30.617791
  272859 |          1 |  1100 | 2018-12-01 11:31:40.746908
  139210 |          2 |  1100 | 2018-11-13 14:24:19.775732
  193796 |          2 |   880 | 2018-11-23 13:17:20.820132

如何在一个查询中选择最小值(价格)及其时间戳,最大值(价格)及其时间戳?

1 个答案:

答案 0 :(得分:1)

您可以两次使用ROW_NUMBER

WITH cte AS (
    SELECT id, product_id, price, timestamp,
        ROW_NUMBER() OVER (ORDER BY price) rn_min,
        ROW_NUMBER() OVER (ORDER BY price DESC) rn_max
    FROM yourTable
)

SELECT 'min' AS label, price, timestamp FROM cte WHERE rn_min = 1
UNION ALL
SELECT 'max', price, timestamp FROM cte WHERE rn_max = 1;

如果您不希望使用minmax标签(价格本身给出了最小值和最大值),那么您可以使用以下方法:

SELECT price, timestamp FROM cte WHERE rn_min = 1 OR rn_max = 1;