We have a table holding the values of a cumulative amount by date, for instance:
| date. | |
| 2015-03-01 | 1.23 |
| 2015-03-04 | 1.98 |
| 2015-03-06 | 2.23 |
And we have a table with all dates we need, for instance:
| date. |
| 2015-03-01 |
| 2015-03-02 |
| 2015-03-03 |
| 2015-03-04 |
| 2015-03-05 |
| 2015-03-06 |
We would like to get:
| date. | |
| 2015-03-01 | 1.23 |
| 2015-03-02 | 1.23 |
| 2015-03-03 | 1.23 |
| 2015-03-04 | 1.98 |
| 2015-03-05 | 1.98 |
| 2015-03-06 | 2.23 |
Is that possible just using SQL itself?
I'm having a bad time trying to figure how to do that.
I have tried some cross joins operations, without success.
Thanks
I realized - it should be even simplier (much simplier) in this particular case.
Try below
SELECT
dates_table.date,
MAX(amounts.amount) OVER(ORDER BY dates_table.date) AS amount
FROM dates_table LEFT JOIN amounts_table
ON dates_table.date = amounts_table.date
As some of you have problem adopting this answer and thinking it doesnt work - I just added below example to "prove" above is working :o)
SELECT
dates.date,
MAX(amounts.amount) OVER(ORDER BY dates.date) AS amount
FROM (
SELECT * FROM
(SELECT '2015-03-01' AS [date]),
(SELECT '2015-03-02' AS [date]),
(SELECT '2015-03-03' AS [date]),
(SELECT '2015-03-04' AS [date]),
(SELECT '2015-03-05' AS [date]),
(SELECT '2015-03-06' AS [date])
) AS dates
LEFT JOIN (
SELECT * FROM
(SELECT '2015-03-01' AS [date], 1.23 AS amount),
(SELECT '2015-03-04' AS [date], 1.98 AS amount),
(SELECT '2015-03-06' AS [date], 2.23 AS amount)
) AS amounts
ON dates.date = amounts.date
Result is:
Row dates_date amount
1 2015-03-01 1.23
2 2015-03-02 1.23
3 2015-03-03 1.23
4 2015-03-04 1.98
5 2015-03-05 1.98
6 2015-03-06 2.23