TSQL 滚动总和与上个月的行数。

问题描述 投票:0回答:1

我有一个表格,上面有每一天的行数,INT列10表示缺勤。我需要计算每行缺勤天数的滚动总和。我使用的是SQL 2016。

行上的日期将是这个月的最后一天,第一天将是过去27到30天之间的东西,这取决于像2月这样的月份。

我已经尝试使用

SUM () OVER (PARTITION BY col1 ORDER by col2 ROWS BETWEEN 30 PRECEDING and CURRENT ROW)

当我们有二月这样的月份时,这将失败。我需要的是一种方法来拥有

ROWS BETWEEN N PRECEDING and CURRENT ROW

其中N是根据行上的日期和一个月前的开始日期计算的。

enter image description here

为了让我的利益尝试,我这里有一个例子脚本。

if object_id ('tempdb..#data') is not null drop table #data

create table #data
(
emp_name varchar(50)
,calendar_date date
,absence INT default(0)
)

-- script to populate table
;WITH Tally (n) AS
(
    select 0 as n
    union
    -- 1000 rows
    SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
    FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
    CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
    CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
)
insert into #data(emp_name, calendar_date)
SELECT 'Dorris Johanssen' as emp_name, cast(DATEADD(dd, n, '2019-01-01') as date) calendar_date
FROM Tally
union
SELECT 'Broderick Snob' as emp_name, cast(DATEADD(dd, n, '2019-01-01') as date) calendar_date
FROM Tally

-- Populate Absence
update #data set absence = 1 where emp_name = 'Dorris Johanssen' and calendar_date between '2020-02-25' and '2020-03-02'
--update #data set absence = 1 where emp_name = 'Dorris Johanssen' and calendar_date between '2020-03-23' and '2020-04-07'
update #data set absence = 1 where emp_name = 'Broderick Snob' and calendar_date between '2020-03-23' and '2020-04-07'

-- Rolling sum of absence for the last one month
select *
, dateadd(dd, 1, dateadd(mm, -1, calendar_date)) as  date_one_month_before
, datediff(dd, dateadd(dd, 1, dateadd(mm, -1, calendar_date)), calendar_date) day_diff
, sum(absence) over (Partition by emp_name order by calendar_date rows between 30 preceding and current row) abs_day 
from #data 
where emp_name = 'Dorris Johanssen'
sql sql-server sql-server-2016
1个回答
0
投票

听起来你想要的是当前月份的累计总和。

select t.*,
       sum(absence) over (partition by emp_name, eomonth(calendar_date) order by calendar_date)
from t
© www.soinside.com 2019 - 2024. All rights reserved.