0

I have an SQL Server table structured as follows :

Table name : calendar. 

Columns :

Calendar Date (smalldatetime)
Working Day (bit)

Calendar date has all dates, structured in the format yyyy-mm-dd. Working day means that I have work if it is a 1, and if it is a weekend or a holiday it is marked as a 0 :).

Example of what I want to retrieve :

Date   NumWorkingDaysInMonthSoFar
------------------------------------
2013-06-01    0 --Due to this being marked a 0 as above (Saturday)
2013-06-02    0 --Due to this being marked a 0 as above (Sunday) -- All 3 of these dates marked as 0
2013-06-03    1 --Due to this being marked a 0 as above (Bank Holiday)
2013-06-04    1
2013-06-05    2
2013-06-06    3

Except I would like the query to work for ALL dates in the calendar - so if I ran it today, it would retrieve the number of working days in the month containing all of the calendar dates in my table above.

All of the information is there, but I am just not sure how to write a query like this or even where to begin, but I think I have gotten the barebones of it below :

SELECT Sum(Working Day)
       WHERE DATEADD(dd, 0, DATEDIFF(mm, 0, CalendarDate)) between
              GETDATE() and START_OF_MONTH
       GROUP BY (Not a clue)
4

1 回答 1

1

SQL Server 2012 直接支持累积和。对于早期版本,您需要执行类似花哨的连接或相关子查询之类的操作。我更喜欢后者,因为我认为它更容易阅读:

select c.[date],
       (select sum(cast(WorkingDay as int))
        from calendar c2
        where year(c.[date]) = year(c2.[date]) and
              month(c.[date]) = month(c2.[date]) and
              c2.[date] <= c.[date]
       ) as NumWorkingDaysInMonth
from calendar c

在 SQL Server 2012 中,您只需执行以下操作:

select c.[date],
       sum(cast(WorkingDay as int)) over (partition by year(c.[date], month[c.date])
                                          order by c.[date]
                                         ) as NumWorkingDaysInMonth
from calendar c
于 2013-06-13T16:01:54.010 回答