在SQL查询中创建行以填充缺少的日期

时间:2013-06-18 01:16:45

标签: date dynamic calendar

我只玩了几个月的SQL,所以请放轻松。

所以我现在得到了以下内容:

SELECT   WorkItems.workDate
       , SUM(WorkItems.hours)as [hours]
       , WorkItems.techID
FROM         Jobs
INNER JOIN WorkItems
ON Jobs.jobID = WorkItems.jobID
INNER JOIN Techs
ON Jobs.techID = Techs.techID
WHERE (WorkItems.workDate BETWEEN @startdate AND @enddate)
AND (WorkItems.techID = 41)
GROUP BY WorkItems.workDate
, WorkItems.techID

返回:

2013-06-03 00:00:00.000 7.00    41
2013-06-05 00:00:00.000 7.00    41
2013-06-06 00:00:00.000 7.50    41
2013-06-07 00:00:00.000 1.00    41

我正在尝试填充查询留下的日期空白以获得类似的内容:

2013-06-03 00:00:00.000 7.00    41
2013-06-04 00:00:00.000 0       41
2013-06-05 00:00:00.000 7.00    41
2013-06-06 00:00:00.000 7.50    41
2013-06-07 00:00:00.000 1.00    41

我已经尝试通过在定义的范围内生成所有内容来添加日期,但现在我得到了重复项。

Declare @t table(Date datetime, hoursWorked int, tech int)

Declare @startdate datetime
Declare @enddate datetime
declare @techID int
Set @startdate='06/02/2013'
Set @enddate='06/07/2013'
Set @techID='41'

Select dateadd(day,number,@startdate) as workDate, 0 as [hours], @techID from master.dbo.spt_values 
where master.dbo.spt_values.type='p' and dateadd(day,number,@startdate)<=@enddate
and dateadd(day,number,@startdate) not in 
(select date from @t)
UNION
SELECT   WorkItems.workDate, SUM(WorkItems.hours)as [hours], WorkItems.techID
FROM         Jobs INNER JOIN
                  WorkItems ON Jobs.jobID = WorkItems.jobID INNER JOIN
                  Techs ON Jobs.techID = Techs.techID
WHERE     (WorkItems.workDate BETWEEN @startdate AND @enddate) AND (WorkItems.techID =     41)
GROUP BY WorkItems.workDate, WorkItems.techID

返回:

2013-06-02 00:00:00.000 0.00    41
2013-06-03 00:00:00.000 0.00    41
2013-06-04 00:00:00.000 0.00    41
2013-06-04 00:00:00.000 7.00    41
2013-06-05 00:00:00.000 0.00    41
2013-06-05 00:00:00.000 7.00    41
2013-06-06 00:00:00.000 0.00    41
2013-06-06 00:00:00.000 7.50    41
2013-06-07 00:00:00.000 0.00    41
2013-06-07 00:00:00.000 1.00    41

很抱歉,如果这个查询非常有用,但我只是试图了解SQL。

感谢。

0 个答案:

没有答案