gpt4 book ai didi

sql - 计算每日使用量

转载 作者:行者123 更新时间:2023-12-01 12:07:14 25 4
gpt4 key购买 nike

我有如下日常使用数据。

enter image description here

我需要为每种 2000 用法重新填充产品。这是预期的结果。

enter image description here

我尝试使用SUM OVER查询来获取每日的先前总使用量,并尝试除以得到2000的倍数。

SELECT Date, Usage,
SUM(Usage) OVER(ORDER BY Date) AS DailyTotal,
CAST(SUM(Usage) OVER(ORDER BY Date) / 2000 AS INT) Div
FROM Transaction

enter image description here

但是,我仍然找不到我必须补充的日期。我该怎么做?

最佳答案

您可以尝试将LAG窗口函数与子查询一起使用。

MS SQL Server 2017架构设置:

create table [Transaction]([Date] date, usage int);

insert into [Transaction] values
('2017-01-01',1373),
('2017-01-02',1387),
('2017-01-03',1509),
('2017-01-04',1523),
('2017-01-05',1537);

查询1 :
SELECT Date, 
Usage,
DailyTotal,
(CASE WHEN LAG(Div,1,Div) OVER(ORDER BY Date) <> Div THEN 1 ELSE 0 END) div
FROM (
SELECT Date, Usage,
SUM(Usage) OVER(ORDER BY [Date]) AS DailyTotal,
CAST(SUM(Usage) OVER(ORDER BY [Date]) / 2000 AS INT) Div
FROM [Transaction]
)t1

Results :
|       Date | Usage | DailyTotal | div |
|------------|-------|------------|-----|
| 2017-01-01 | 1373 | 1373 | 0 |
| 2017-01-02 | 1387 | 2760 | 1 |
| 2017-01-03 | 1509 | 4269 | 1 |
| 2017-01-04 | 1523 | 5792 | 0 |
| 2017-01-05 | 1537 | 7329 | 1 |

关于sql - 计算每日使用量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55332012/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com