计算每日使用量

时间:2019-03-25 06:01:33

标签: sql sql-server

我有如下日常使用数据。

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

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

2 个答案:

答案 0 :(得分:3)

您可以尝试将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 |

答案 1 :(得分:1)

使用row_number() and comparison

在下面尝试

DEMO

select *,case when DailyTotal<2000*(case when rn=1 then 1 else rn-1 end) then 0 else 1 end
as refill from
(
SELECT Dateval, Usage,
       SUM(Usage) OVER(ORDER BY Dateval) AS DailyTotal,
       row_number() over(order by dateval) rn
FROM t1
)AA

输出:

Dateval             Usage   DailyTotal  rn  refill
01/01/2017 00:00:00 1373    1373        1   0
02/01/2017 00:00:00 1387    2760        2   1
03/01/2017 00:00:00 1509    4269        3   1
04/01/2017 00:00:00 1523    5792        4   0