【发布时间】:2013-06-10 22:14:43
【问题描述】:
我有两个运行良好的查询。我想将这两个查询合并在一起,但我不知道该怎么做。
我有一个结构如下的 SQL Server 表:
Table name : calendar.
列:
Calendar Date (smalldatetime)
Working Day (bit)
日历日期包含所有日期,格式为 yyyy-mm-dd。工作日表示我有工作,如果是 1,如果是周末或节假日,则标记为 0:)。
我要检索的示例:
CalendarDate NumWorkingDaysInMonthSoFar NumWorkingDaysInThisMonthTotal
------------------------------------
2013-06-01 0 (--Due to this being marked a 0 as above (Saturday)) 22
2013-06-02 0 (--Due to this being marked a 0 as above (Sunday) -- All 3 of these dates marked as 0) 22
2013-06-03 1 (--Due to this being marked a 0 as above (Bank Holiday)) 22
2013-06-04 1 22
2013-06-05 2 22
2013-06-06 3 22
我有两个查询分别做这两件事,但我正在努力弄清楚如何将两者结合起来以产生上述结果集。
这是返回 NumberWorkingDaysInThisMonthTotal 的查询(示例中为 22,每个月应该是不同的值):
SELECT
SUM(WorkingDay) As NumWorkingDaysInThisMonthTotal
FROM [calendar]
GROUP BY YEAR(CalendarDate), MONTH(CalendarDate)
并返回该月到目前为止的每一天的工作日数(每个工作日加一个,每个月初重置):
select c.[CalendarDate],
(select sum(cast(WorkingDay as int))
from calendar c2
where year(c.[CalendarDate]) = year(c2.[CalendarDate]) and
month(c.[CalendarDate]) = month(c2.[CalendarDate]) and
c2.[CalendarDate] <= c.[CalendarDate]
) as NumWorkingDaysInMonthSoFar
from calendar c
如何将这些组合起来以生成上述结果集?我真的很感谢您提供一些有关您如何弄清楚如何做到这一点的信息-在这种特定情况下都是如此;并且在您获得 SQL 背景的地方,以便我可以提高自己。非常感谢。
【问题讨论】:
标签: sql sql-server database sql-server-2005 select