SQL Server How To Generate the Data for missing Dates till current date

mw3dktmi  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(84)

I have a use case, where the data/orders from source comes everyday also may not on few days. I want to generate the data for all the dates till today as below
| Sales | Order_Qunty | Date |
| ------------ | ------------ | ------------ |
| 20 | 20000 | 20231202 |
| 30 | 30000 | 20231205 |
| 30 | 40000 | 20231207 |

Expected Output

SalesOrder_QuntyDate
202000020231202
0000020231203
0000020231204
303000020231205
0000020231206
304000020231207
0000020231208
0000020231209
0000020231210
0000020231211
0000020231212

I want to Generate the data for each date till today using the above source table and the Date table which has the date range from 19000101 - 20991231 Please Advise

Thanks in advance

jm2pwxwz

jm2pwxwz1#

You can use a LEFT JOIN between the Date table and the source table. This will fill in missing dates with zeros for Sales and Order_Quantity .

SELECT COALESCE(S.Sales, 0) AS Sales, COALESCE(S.Order_Qunty, '0000') AS Order_Qunty, D.Date
FROM DateTable D
LEFT JOIN SourceTable S ON D.Date = S.Date
WHERE D.Date BETWEEN '20230101' AND '20231212' -- Date range from the SourceTable
ORDER BY D.Date;
6jjcrrmo

6jjcrrmo2#

This is implementation of PostgreSQL.

WITH date_sequence AS (
    SELECT generate_series(
        (SELECT MIN(date_column) FROM your_existing_data), 
        CURRENT_DATE, 
        '1 day'::interval
    )::DATE AS date_column
)
SELECT COALESCE(your_existing_data.Sales, 0) AS Sales, COALESCE(your_existing_data.Order_Qunty, '0000') AS Order_Qunty, ds.date_column
FROM date_sequence ds
LEFT JOIN your_existing_data ON ds.date_column = your_existing_data.date_column
ORDER BY ds.date_column;

In SqlServer

WITH DateSequence AS (
    SELECT MIN(date_column) AS date_column
    FROM your_existing_data
    
    UNION ALL
    
    SELECT DATEADD(DAY, 1, date_column)
    FROM DateSequence
    WHERE DATEADD(DAY, 1, date_column) <= GETDATE()
)
SELECT COALESCE(your_existing_data.Sales, 0) AS Sales, COALESCE(your_existing_data.Order_Qunty, '0000') AS Order_Qunty, ds.date_column
FROM DateSequence ds
LEFT JOIN your_existing_data ON ds.date_column = your_existing_data.date_column
ORDER BY ds.date_column;

Please replace your_existing_data to your real table name.

相关问题