[英]SQL get corresponding data where min or max value
Here is my data structure这是我的数据结构
ID_group ID_组 | Date日期 | Price价格 |
---|---|---|
1 1个 | 20/11/2022 20/11/2022 | 3 3个 |
1 1个 | 19/11/2022 19/11/2022 | 4 4个 |
2 2个 | 18/11/2022 18/11/2022 | 42 42 |
2 2个 | 19/11/2022 19/11/2022 | 2 2个 |
1 1个 | 21/11/2022 21/11/2022 | 2 2个 |
I want to make a table in order to get my data in this format:我想制作一个表格以便以这种格式获取我的数据:
ID_group ID_组 | MaxPrice最高价 | MaxPriceDate最大价格日期 | MinPrice最低价格 | MinPriceDate最低价格日期 |
---|---|---|---|---|
1 1个 | 4 4个 | 19/11/2022 19/11/2022 | 3 3个 | 20/11/2022 20/11/2022 |
2 2个 | 42 42 | 18/11/2022 18/11/2022 | 2 2个 | 19/11/2022 19/11/2022 |
Here is what I have now:这是我现在拥有的:
select ID_group,
max(price) MaxPrice,
'' MaxPriceDate,
min(price) MinPrice,
'' MinPriceDate
from table
group by ID_group
We can use ROW_NUMBER
here, along with pivoting logic:我们可以在这里使用ROW_NUMBER
以及旋转逻辑:
WITH cte AS (
SELECT t.*, ROW_NUMBER() OVER (PARTITION BY ID_group ORDER BY Price) rn1,
ROW_NUMBER() OVER (PARTITION BY ID_group ORDER BY Price DESC) rn2
FROM yourTable t
)
SELECT
ID_group,
MAX(CASE WHEN rn2 = 1 THEN Price END) AS MaxPrice,
MAX(CASE WHEN rn2 = 1 THEN "Date" END) AS MaxPriceDate,
MAX(CASE WHEN rn1 = 1 THEN Price END) AS MinPrice,
MAX(CASE WHEN rn1 = 1 THEN "Date" END) AS MinPriceDate
FROM cte
GROUP BY ID_group
ORDER BY ID_group;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.