例如,我有以下销售表:
周 | 销售 |
---|---|
1 | 10 |
1 | 15 |
2 | 5 |
2 | 10 |
3 | 10 |
3 | 20 |
4 | 5 |
4 | 10 |
5 | 15 |
5 | 10 |
我想要一个像这样的 SQL 查询:
SELECT '1-3' AS period, SUM(sales)
FROM sale
WHERE 1<=week AND week<=3
GROUP BY period
UNION ALL
SELECT '2-4' AS period, SUM(sales)
FROM sale
WHERE 2<=week AND week<=4
GROUP BY period
UNION ALL
SELECT '3-5' AS period, SUM(sales)
FROM sale
WHERE 3<=week AND week<=5
GROUP BY period
当滚动窗口数量较多时,上面的SQL查询会很麻烦。有解决办法吗?
我尝试考虑使用卡特里积。但是,它会生成一些不需要的行。
如果您的 RDBMS 支持表/行值构造函数(例如,在 SQL Server 中您有
values
子句),那就非常简单了。这是一个例子:
select concat(list.a, '-', list.b) as period, sum(t.sales) as total
from (values
(1, 3),
(2, 4),
(3, 5)
) as list(a, b)
left join t on t.week between list.a and list.b
group by list.a, list.b