0

次のような構造の 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)
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 に答える