+-------------------------+
| id date value comments |
+-------------------------+
| 1 d1 10 c1 |
| 1 d2 20 c2 |
| 1 d3 30 c3 |
| 2 d7 70 c4 |
+-------------------------+
想要编写一个SQL来创建如下所示的展平表:
id | max_value | date_of_max_value | min_value | date_of_min_value
答案 0 :(得分:0)
大多数数据库都支持窗口功能,例如row_number()
。这让您可以使用条件聚合来解决这个问题:
select id, max(value) as max_value,
max(case when seqnum_desc = 1 then date end) as date_max_value,
min(value) as min_value,
max(case when seqnum_asc = 1 then date end) as date_min_value
from (select t.*,
row_number() over (partition by id order by value asc) as seqnum_asc,
row_number() over (partition by id order by value desc) as seqnum_desc
from t
) t
group by id;