使用 SQL 合并滞后值计算比率
Calculate a ratio using SQL incorporating lag values
我有一个table这样的
对于每一天,我需要计算(当 cat=4 时的那一天的 val 总和)/(当 cat=3 时前一天的 val 总和)的比率。
你能告诉我如何计算吗?
我可以这样分别计算分子和分母:
select Date, sum(val) as bal1 from performance
where cat=4 group by Date
select Date, sum(val) as bal2 from performance
where cat=3 group by Date
但我不确定如何将它们结合起来以获得我上面提到的比率。可能我需要按日期加入两个结果。
任何指导将不胜感激。
我们可以尝试使用 LAG()
如下:
WITH cte AS (
SELECT *, LAG(cat) OVER (PARTITION BY Date ORDER BY Date) lag_cat,
LAG(val) OVER (PARTITION BY Date ORDER BY Date) lag_val
FROM performance
)
SELECT
Date,
SUM(CASE WHEN cat = 4 THEN val ELSE 0 END) /
SUM(CASE WHEN lag_cat = 3 THEN lag_val ELSE 0 END) AS ratio
FROM cte
GROUP BY Date;
您可以将聚合与 LAG()
window 函数结合使用:
SELECT Date,
SUM(CASE WHEN cat = 4 THEN val END) /
LAG(SUM(CASE WHEN cat = 3 THEN val END)) OVER (ORDER BY Date) ratio
FROM performance
GROUP BY Date;
参见demo。
我有一个table这样的
对于每一天,我需要计算(当 cat=4 时的那一天的 val 总和)/(当 cat=3 时前一天的 val 总和)的比率。
你能告诉我如何计算吗?
我可以这样分别计算分子和分母:
select Date, sum(val) as bal1 from performance
where cat=4 group by Date
select Date, sum(val) as bal2 from performance
where cat=3 group by Date
但我不确定如何将它们结合起来以获得我上面提到的比率。可能我需要按日期加入两个结果。
任何指导将不胜感激。
我们可以尝试使用 LAG()
如下:
WITH cte AS (
SELECT *, LAG(cat) OVER (PARTITION BY Date ORDER BY Date) lag_cat,
LAG(val) OVER (PARTITION BY Date ORDER BY Date) lag_val
FROM performance
)
SELECT
Date,
SUM(CASE WHEN cat = 4 THEN val ELSE 0 END) /
SUM(CASE WHEN lag_cat = 3 THEN lag_val ELSE 0 END) AS ratio
FROM cte
GROUP BY Date;
您可以将聚合与 LAG()
window 函数结合使用:
SELECT Date,
SUM(CASE WHEN cat = 4 THEN val END) /
LAG(SUM(CASE WHEN cat = 3 THEN val END)) OVER (ORDER BY Date) ratio
FROM performance
GROUP BY Date;
参见demo。