PostgreSQL - 如何在单个查询中获取列的最小值和最大值以及与它们关联的行?
PostgreSQL - How to get min and max values of a column and the rows associated with them in a single query?
我有一个名为 'product' 的 table,其中包含列 -
product_name、sale_price、sale_date
我想获取最小值(sale_price) 和最大值(sale_price) 以及最低价和最高价的销售日期。
我有这样的查询:
SELECT sale_price, sale_date FROM product WHERE (sale_price) IN (
SELECT
min(sale_price)
FROM product
WHERE product_name = 'PHONE'
) AND product_name = 'PHONE'
UNION
SELECT sale_price, sale_date FROM product WHERE (sale_price) IN (
SELECT
max(sale_price)
FROM product
WHERE product_name = 'PHONE'
) AND product_name = 'PHONE'
我确信有一种优雅的方式来查询它。
任何帮助深表感谢。
提前致谢!
您可以使用 window 个函数:
select sale_price, sale_date
from (
select p.*,
rank() over(order by sale_price) rn_asc,
rank() over(order by sale_price desc) rn_desc
from product p
where product_name = 'PHONE'
) p
where 1 in (rn_asc, rn_desc)
此答案是根据您对问题的描述得出的。你没有解释 table daily_price
在查询中代表什么,所以查询不使用它。
如果您希望结果在一行中,则可以进行条件聚合:
select
min(sale_price) min_sale_price, min(sale_date) filter(where rn_asc = 1) min_sale_date,
max(sale_price) min_sale_price, max(sale_date) filter(where rn_desc = 1) max_sale_date
from (
select p.*,
rank() over(order by sale_price) rn_asc,
rank() over(order by sale_price desc) rn_desc
from product p
where product_name = 'PHONE'
) p
where 1 in (rn_asc, rn_desc)
我有一个名为 'product' 的 table,其中包含列 - product_name、sale_price、sale_date
我想获取最小值(sale_price) 和最大值(sale_price) 以及最低价和最高价的销售日期。
我有这样的查询:
SELECT sale_price, sale_date FROM product WHERE (sale_price) IN (
SELECT
min(sale_price)
FROM product
WHERE product_name = 'PHONE'
) AND product_name = 'PHONE'
UNION
SELECT sale_price, sale_date FROM product WHERE (sale_price) IN (
SELECT
max(sale_price)
FROM product
WHERE product_name = 'PHONE'
) AND product_name = 'PHONE'
我确信有一种优雅的方式来查询它。 任何帮助深表感谢。 提前致谢!
您可以使用 window 个函数:
select sale_price, sale_date
from (
select p.*,
rank() over(order by sale_price) rn_asc,
rank() over(order by sale_price desc) rn_desc
from product p
where product_name = 'PHONE'
) p
where 1 in (rn_asc, rn_desc)
此答案是根据您对问题的描述得出的。你没有解释 table daily_price
在查询中代表什么,所以查询不使用它。
如果您希望结果在一行中,则可以进行条件聚合:
select
min(sale_price) min_sale_price, min(sale_date) filter(where rn_asc = 1) min_sale_date,
max(sale_price) min_sale_price, max(sale_date) filter(where rn_desc = 1) max_sale_date
from (
select p.*,
rank() over(order by sale_price) rn_asc,
rank() over(order by sale_price desc) rn_desc
from product p
where product_name = 'PHONE'
) p
where 1 in (rn_asc, rn_desc)