基于NULL月份的一年中的月份的累积总和

时间:2013-12-02 22:25:00

标签: sql-server tsql sql-server-2012 pivot

我正在尝试返回系统中为所选销售人员和所选年份输入的所有潜在客户的摘要。输入的日期是一个日期时间,我正在转动数据,以显示它按月拆分。

第一个查询返回每月推荐的数量,其中第二个查询显示累计输入的推荐数量。除了包含空值的月份外,我已正确显示它们。具有空值的月份我想在这种情况下显示上个月的值。

我目前正在使用T-SQL 2012。

SELECT 'Number of Referrals' AS Measure,[1] AS Jan, [2] AS Feb, [3] AS Mar, [4] AS Apr, 
[5] AS May, [6] AS Jun, [7] AS Jul, [8] AS Aug, [9] AS Sep, [10] AS Oct, [11] AS Nov, [12] AS Dec
FROM
(
SELECT ISNULL(COUNT(DISTINCT CSCU.ClientID), 0) AS Referrals, DATEPART(M, CS.DateAdded) AS Months
FROM ClientTracker.dbo.ClientService CS
INNER JOIN ClientTracker.dbo.ClientServiceContactUser CSCU
ON CS.ClientID = CSCU.ClientID
AND CS.ServiceID = CSCU.ServiceID
WHERE UserId = @UserID
AND DATEPART(YEAR, CS.DateAdded) = @Year
AND CSCU.ServiceID = 30
GROUP BY DATEPART(M, CS.DateAdded)
) AS S
PIVOT
(
SUM(Referrals)
FOR [Months] IN ([1], [2], [3], [4], 
    [5], [6], [7], [8], [9], [10], [11], [12])
)AS PV

UNION

SELECT 'Number of Referrals Cumulative' AS Measure,[1] AS Jan, [2] AS Feb, [3] AS Mar, [4] AS Apr, [5] AS May, [6] AS Jun, [7] AS Jul, [8] AS Aug, [9] AS Sep, [10] AS Oct, [11] AS Nov, [12] AS Dec
FROM
(
SELECT DATEPART(M, CS.DateAdded) AS Months, 
SUM(COUNT(CSCU.ClientID)) OVER (ORDER BY DATEPART(M, CS.DateAdded)) AS Cumulative
FROM ClientTracker.dbo.ClientService CS
INNER JOIN ClientTracker.dbo.ClientServiceContactUser CSCU
ON CS.ClientID = CSCU.ClientID
AND CS.ServiceID = CSCU.ServiceID
WHERE UserId = @UserID
AND DATEPART(YEAR, CS.DateAdded) = @Year
AND CSCU.ServiceID = 30
GROUP BY DATEPART(M, CS.DateAdded)
) AS S
PIVOT
(
SUM(Cumulative)
FOR [Months] IN ([1], [2], [3], [4], 
    [5], [6], [7], [8], [9], [10], [11], [12])
)AS PV

1 个答案:

答案 0 :(得分:0)

您可以使用coalesce()功能。它接收尽可能多的参数并返回第一个非空值。 因此,在您的示例中,将查询重写为

SELECT 'Number of Referrals' AS Measure,[1] AS Jan, coalesce([2],[1]) AS Feb, .....

COALESCE() on MSDN