0

I am trying to return a summary of all prospects entered in the system for a chosen sales person and a chosen year. The date entered is a datetime and I am pivoting the data to show it broken by month to month.

The first query returns the number of referrals each month, where the second query shows how many referrals entered cumulatively. I have gotten them properly showing with the exception of months containing null values. Months with null values I want to show the value of the previous month in that case.

I am currently using 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 Answer 1

0

You could use coalesce() function. It takes in as many parameters and returns the first non null values. So for in your example rewrite the query to

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

COALESCE() on MSDN

1
  • I forgot about COALESCE, that's exactly what I needed! Thank you!
    – cpiasecki
    Dec 3, 2013 at 15:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.