例如,对于表格如:
ID | col_a | col_b | col_c
=============================
1 |5.0 |7.0 |3
2 |3.0 |6.8 |5
我需要找到col_a / col_b的值,col_c上的运行总数小于给定值。
到目前为止,我有:
select MAX(running_total) as max FROM (select (col_a / col_b) as val, SUM(col_c)
OVER (ORDER BY value ROWS UNBOUNDED PRECEDING) as running_total FROM tableName)
WHERE running_total < 50;
这给了我最大的运行总数,但我还需要val(col_a / col_b)用于达到此running_total的行。
我正在使用Amazon Redshift进行此查询,与mysql不同,我不会让val在外部select语句中放置val,而不在val上添加group by子句。我无法添加group by子句,这将改变查询的整个语义。
我找到了类似问题的解决方案 - Fetch the row which has the Max value for a column
大多数情况下,这些解决方案建议我们使用相同的表连接然后匹配列的值,但是计算running_total列并对其进行连接,我必须再次计算它?听起来相当昂贵。
答案 0 :(得分:2)
你可以这样做。窗口有助于救援。
只需添加另一层子查询,即计算每行的最大运行总计。然后使用where
子句获取它们匹配的行:
select t.*
from (select t.*,
max(running_total) over () as maxrt
FROM (select (col_a / col_b) as val,
SUM(col_c) OVER (ORDER BY value ROWS UNBOUNDED PRECEDING
) as running_total
FROM tableName
) t
WHERE running_total < 50
) t
where running_total = maxrt;