0

I have below query which works fine, it displays all the values for that particular location how much was the refund amount. However, if I want to show monthly report, I need to show those days were no refund is there in my Table 1 and display zero values for the same:

SELECT businessDate AS 'Business Date'
    ,Sum(convert(DECIMAL, ISNULL(T1.Amount, 0)) * 1) AS 'Refund Amount'
FROM table1 T1
WHERE (
        (T1.id = '1')
        AND (T1.businessDate BETWEEN '20160201' AND '20160229')
        AND (T1.Amount IS NOT NULL)
        )
GROUP BY T1.businessDate

my Current output is:

Business Date   Refund Amount
  20160202            14
  20160203            19

It should be:

Business Date   Refund Amount
  20160201             0
  20160202            14
  20160203            19

so how to fix my query to cater the above??

Smandoli
  • 6,919
  • 3
  • 49
  • 83
Omran Moh'd
  • 87
  • 1
  • 11

1 Answers1

1

I would use a recursive CTE as follows:

WITH cte
AS
    (
        SELECT CAST('2016-02-01' AS date) [Date]
        UNION ALL
        SELECT DATEADD(DAY, 1, [Date])
        FROM cte
        WHERE DATEADD(DAY, 1, [Date]) <= '2016-02-29'
    )

SELECT
    cte.[Date] [Business Date]
    , SUM(CONVERT(decimal, ISNULL(T1.Amount, 0)) * 1) [Refund Amount]
FROM
    cte
    LEFT JOIN (SELECT * FROM table1 WHERE id = 1) T1 ON cte.[Date] = T1.businessDate
GROUP BY cte.[Date]
Chris Mack
  • 5,148
  • 2
  • 12
  • 29