1

我在 SQL Server 2008 中工作。我正在编写一个每周聚合数据的存储过程。

聚合代码是

ALTER PROCEDURE [dbo].[ups_URLBatchStats] 
   (@startDate datetime, @endDate datetime,@source varchar(8))
AS BEGIN
    SELECT 
       DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6) AS [Week Commencing], 
       SUM(Unresolved) AS Unresolved,
       SUM(Resolved) AS Resolved,
       SUM(TurkSpend) AS TurkSpend
    FROM 
       dbo.V_URLBatchStats 
    WHERE
       ScheduleDate BETWEEN @startDate AND @endDate 
       AND Source = ISNULL(@source, Source)
    GROUP BY
       DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6)
    ORDER BY 
       DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6)
END

显示它给了我正确的结果,但是如果任何一周都没有数据,我必须在列中显示它的值为“0”。

那么我该如何处理这些跳过的每周行呢?

提前致谢。

4

2 回答 2

1

您可以RIGHT JOIN使用带有生成行号的 sysobjects 您的周列:

SELECT o.Num AS [Week Commencing], SUM(Unresolved) AS Unresolved,sum(Resolved)as Resolved,sum(TurkSpend) as TurkSpend 
FROM dbo.V_URLBatchStats s
RIGHT JOIN (SELECT ROW_NUMBER() OVER (ORDER BY object_id) as [Num] FROM sysobjects) o 
    on DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6) = o.Num
WHERE ScheduleDate between @startDate and @endDate 
AND Source=ISNULL(@source,Source)
GROUP BY DATEADD(wk, DATEDIFF(wk, 0, ScheduleDate), 6), o.Num
ORDER BY 1

请注意,这是从内存中编写的,未经测试,但原理应该有效。

于 2012-10-12T07:37:09.027 回答
1

看来您当前选择了错误的一周,我尝试解决此问题:

SELECT dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, @startdate)-1, 6)) AS [Week Commencing], 
coalesce(SUM(Unresolved), 0) AS Unresolved,
coalesce(sum(Resolved), 0)as Resolved,
coalesce(sum(TurkSpend), 0) as TurkSpend
FROM dbo.V_URLBatchStats 
right join
master..spt_values 
on ScheduleDate between @startDate and @endDate and Source=ISNULL(@source,Source)
where type = 'P' and dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, @startdate)-1, 6)) <= @enddate
GROUP BY dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, @startdate)-1, 6))
ORDER BY dateadd(wk, number, DATEADD(wk, DATEDIFF(wk, 0, @startdate)-1, 6))
于 2012-10-12T08:56:31.267 回答