I have a table with the following entries,
| ID | date | Frequency |
|---|---|---|
| 1 | '2014-05-18' | 5 |
| 1 | '2014-06-19' | 4 |
| 1 | '2014-07-20' | 25 |
| 2 | '2014-05-20' | 7 |
| 3 | '2014-05-18' | 4 |
| 3 | '2014-06-20' | 1 |
| 4 | '2014-05-18' | 6 |
I am trying to extract the values between two dates in this case it happens to be. 2014-05-18 to 2014-07-20. The select output should have an entry for every month, if any of the month is not having a value it should default to zero for that month and that date should be the last day of that particular month.
The expected output is
| ID | date | Frequency |
|---|---|---|
| 1 | '2014-05-18' | 5 |
| 1 | '2014-06-19' | 4 |
| 1 | '2014-07-20' | 25 |
| 2 | '2014-05-20' | 7 |
| 2 | '2014-06-30' | 0 |
| 2 | '2014-07-31' | 0 |
| 3 | '2014-05-18' | 4 |
| 3 | '2014-06-20' | 1 |
| 3 | '2014-07-31' | 0 |
| 4 | '2014-05-18' | 6 |
| 4 | '2014-06-30' | 0 |
| 4 | '2014-07-31' | 0 |
I have tried using this but It give the list for all the days of that month, But I am interested only in the Last day of the month.
;WITH n AS
(
SELECT n = 0
UNION ALL
SELECT n + 1 FROM n
WHERE n < DATEDIFF(DAY, '20140518', '20140720')
),
range AS
(
SELECT [date] = DATEADD(DAY, n,'20140518') FROM n
),
IDs AS
(
SELECT ID
FROM dbo.MyTable AS t
INNER JOIN range
ON t.[date] = range.[date]
GROUP BY ID
)
SELECT
IDs.ID,
range.[date],
Frequency = COALESCE(t.Frequency, 0)
FROM range CROSS JOIN IDs
LEFT OUTER JOIN dbo.MyTable AS t
ON t.[date] = range.date
AND IDs.ID = t.ID;