SQL:如何 select 基于 window 帧中聚合 min/max 值的列值(包括前面的行)
SQL: How to select a column-value based on an aggregate min/max value in a window frame (including preceding rows)
我有以下 table:
| Date | Value | Name | AnticipatedValue |
| -------- | ------- | ---- | ---------------- |
| 27.11.20 | 639.600 | col1 | |
| 30.11.20 | 638.300 | col2 | |
| 01.12.20 | 638.000 | col3 | col1 |
| 02.12.20 | 642.600 | col4 | col1 |
| 03.12.20 | 646.200 | col5 | col1 |
| 04.12.20 | 651.900 | col6 | col4 |
| 07.12.20 | 651.800 | col7 | col4 |
| 08.12.20 | 643.800 | col8 | col6 |
| 09.12.20 | 654.250 | col9 | col6 |
我想要第 2 和第 5 个 preceding[= 之间具有最大 value 的行中的 name 42=]行。 AnticipatedValue 列显示了我想要的结果。
我目前正在使用 window 函数来获取该示例中的最大值 value,但是我缺少获取相应 的方法最大 值 的名称。
我当前的代码如下所示:
MAX(value) OVER (ORDER BY date ROWS BETWEEN 5 PRECEDING AND 2 PRECEDING)
我认为对我最有帮助的是,如果我能够在 window 框架本身的 inside 中执行另一个 ORDER BY。然后我可以通过按值降序使用订单并取我得到的名字。然而,这在 sql.
中的聚合函数中是不可能/实现的
在我看来,使用子查询来获取相应的名称也很困难,因为我仍然必须在子查询内应用 window 框架(即第 2 行和第 5 行之前)。
我正在使用 Postgres 12.6。
如果您能就此 sql 谜语提供任何帮助,我将不胜感激。我觉得我离解决方案不远了,但是找不到任何优雅的方法。
更新
我采用了 Gordon Linoff 的解决方案并通过使用左连接并添加限制 1 来调整它以获得我想要的上述 table:
select t.*, t2.*
from t left join lateral
(select t2.name, t2.value
from (select t2.name, t2.value
from t t2
where t2.date < t.date
order by t2.date desc
offset 1 fetch first 4 rows only
) t2
order by value desc
limit 1
) t2 ON true;
您可以使用横向连接:
select t.*, t2.*
from t cross join lateral
(select t2.*
from (select t2.name, t2.value
from t t2
where t2.date < t.date
order by t2.date desc
offset 1 fetch first 4 rows only
) t2
order by value desc
) t2;
我有以下 table:
| Date | Value | Name | AnticipatedValue |
| -------- | ------- | ---- | ---------------- |
| 27.11.20 | 639.600 | col1 | |
| 30.11.20 | 638.300 | col2 | |
| 01.12.20 | 638.000 | col3 | col1 |
| 02.12.20 | 642.600 | col4 | col1 |
| 03.12.20 | 646.200 | col5 | col1 |
| 04.12.20 | 651.900 | col6 | col4 |
| 07.12.20 | 651.800 | col7 | col4 |
| 08.12.20 | 643.800 | col8 | col6 |
| 09.12.20 | 654.250 | col9 | col6 |
我想要第 2 和第 5 个 preceding[= 之间具有最大 value 的行中的 name 42=]行。 AnticipatedValue 列显示了我想要的结果。
我目前正在使用 window 函数来获取该示例中的最大值 value,但是我缺少获取相应 的方法最大 值 的名称。 我当前的代码如下所示:
MAX(value) OVER (ORDER BY date ROWS BETWEEN 5 PRECEDING AND 2 PRECEDING)
我认为对我最有帮助的是,如果我能够在 window 框架本身的 inside 中执行另一个 ORDER BY。然后我可以通过按值降序使用订单并取我得到的名字。然而,这在 sql.
中的聚合函数中是不可能/实现的在我看来,使用子查询来获取相应的名称也很困难,因为我仍然必须在子查询内应用 window 框架(即第 2 行和第 5 行之前)。
我正在使用 Postgres 12.6。
如果您能就此 sql 谜语提供任何帮助,我将不胜感激。我觉得我离解决方案不远了,但是找不到任何优雅的方法。
更新 我采用了 Gordon Linoff 的解决方案并通过使用左连接并添加限制 1 来调整它以获得我想要的上述 table:
select t.*, t2.*
from t left join lateral
(select t2.name, t2.value
from (select t2.name, t2.value
from t t2
where t2.date < t.date
order by t2.date desc
offset 1 fetch first 4 rows only
) t2
order by value desc
limit 1
) t2 ON true;
您可以使用横向连接:
select t.*, t2.*
from t cross join lateral
(select t2.*
from (select t2.name, t2.value
from t t2
where t2.date < t.date
order by t2.date desc
offset 1 fetch first 4 rows only
) t2
order by value desc
) t2;