tsql上个月行的滚动求和

pcww981p  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(438)

我有一个表,表中有每天的行,int列为1/0,表示没有。我需要计算每行缺勤天数的滚动总和。我正在使用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是基于行上的日期和一个月前的开始日期计算的。

为了便于我尝试,这里有一个示例脚本:

  1. if object_id ('tempdb..#data') is not null drop table #data
  2. create table #data
  3. (
  4. emp_name varchar(50)
  5. ,calendar_date date
  6. ,absence INT default(0)
  7. )
  8. -- script to populate table
  9. ;WITH Tally (n) AS
  10. (
  11. select 0 as n
  12. union
  13. -- 1000 rows
  14. SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL))
  15. FROM (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) a(n)
  16. CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) b(n)
  17. CROSS JOIN (VALUES(0),(0),(0),(0),(0),(0),(0),(0),(0),(0)) c(n)
  18. )
  19. insert into #data(emp_name, calendar_date)
  20. SELECT 'Dorris Johanssen' as emp_name, cast(DATEADD(dd, n, '2019-01-01') as date) calendar_date
  21. FROM Tally
  22. union
  23. SELECT 'Broderick Snob' as emp_name, cast(DATEADD(dd, n, '2019-01-01') as date) calendar_date
  24. FROM Tally
  25. -- Populate Absence
  26. update #data set absence = 1 where emp_name = 'Dorris Johanssen' and calendar_date between '2020-02-25' and '2020-03-02'
  27. --update #data set absence = 1 where emp_name = 'Dorris Johanssen' and calendar_date between '2020-03-23' and '2020-04-07'
  28. update #data set absence = 1 where emp_name = 'Broderick Snob' and calendar_date between '2020-03-23' and '2020-04-07'
  29. -- Rolling sum of absence for the last one month
  30. select *
  31. , dateadd(dd, 1, dateadd(mm, -1, calendar_date)) as date_one_month_before
  32. , datediff(dd, dateadd(dd, 1, dateadd(mm, -1, calendar_date)), calendar_date) day_diff
  33. , sum(absence) over (Partition by emp_name order by calendar_date rows between 30 preceding and current row) abs_day
  34. from #data
  35. where emp_name = 'Dorris Johanssen'
hwamh0ep

hwamh0ep1#

听起来你想要的是本月的累计金额:

  1. select t.*,
  2. sum(absence) over (partition by emp_name, eomonth(calendar_date) order by calendar_date)
  3. from t

相关问题