运行 SQL 总计(基于日期)

Running total in SQL based on date

所以我有以下两列,我想在 SQL 中按日期创建 运行 总列 - 这是一个小片段

creation date is_registered
2021-03-30 1
2021-03-30 1
2021-03-31 1
2021-03-31 1

我似乎遇到的问题是日期有时间戳并且 reg 列是位格式,所以我尝试了以下查询

with reg as(      
    select
        cast([created_at] as date) as 'date',
        sum(cast([is_registered] as int)) as 'sum_of_reg'
    FROM [dbo].[Registrations]
    group by [created_at]
)
select
    [date],
    sum_of_reg,
    sum(sum_of_reg) over (order by [date]) as 'running total'
FROM reg
group by [date], sum_of_entries
order by [date] asc

但是 return 如下:

date sum of reg running total
2021-03-30 1 1
2021-03-30 1 1
2021-03-31 2 3

我愿意return

date sum of reg running total
2021-03-30 2 1
2021-03-31 2 3

它不会将日期组合成一个不同的值,而是会两次显示相同的日期。

我认为由于时间戳,它仍然单独处理日期,但不确定如何解决它

如有任何建议,我们将不胜感激!

您在 reg CTE 中的分组子句错误,您需要 cast([created_at] as date).

外面的group by不是必须的

The default window in an OVER clause (when there is an ORDER BY) is unfortunately RANGE UNBOUNDED PRECEDING, which is rarely what people expect.
You must specify ROWS UNBOUNDED PRECEDING explicitly.

with reg as(      
    select
        cast([created_at] as date) as [date],
        sum(cast([is_registered] as int)) as [sum_of_reg]
    FROM [dbo].[Registrations]
    group by cast([created_at] as date)
)
select
    [date],
    sum_of_reg,
    sum(sum_of_reg) over (order by [date] ROWS UNBOUNDED PRECEDING) as [running total]
FROM reg
order by [date] asc

你甚至可以在一个关卡中做到这一点

select
    cast([created_at] as date) as [date],
    sum(cast([is_registered] as int)) as [sum_of_reg],
    sum(sum(cast([is_registered] as int)))
      over (order by [date] ROWS UNBOUNDED PRECEDING) as [running total]
FROM [dbo].[Registrations]
group by cast([created_at] as date)
order by [date] asc