只有两列的困难SELECT语句

时间:2013-06-13 15:56:31

标签: sql sql-server database sql-server-2005 select

我有一个SQL Server表,结构如下:

Table name : calendar. 

专栏:

Calendar Date (smalldatetime)
Working Day (bit)

日历日期包含所有日期,格式为yyyy-mm-dd。工作日意味着我有工作,如果它是1,如果是周末或假日,它被标记为0:)。

我要检索的内容示例:

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

除了我希望查询适用于日历中的所有日期 - 所以如果我今天运行它,它将检索包含上表中所有日历日期的月份工作日数。

所有信息都在那里,但我不知道如何编写这样的查询,甚至不知道从哪里开始,但我想我已经得到了下面的准系统:

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

1 个答案:

答案 0 :(得分: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