sqlsql-serversql-server-2019

List dates between start and end date in SQL then merge data based on a calendar date


I have a table with purchasing data, for example this below. The purchased items are for the entire year, so there are hundreds of items. I'm looking for a way to list all of the dates of the month, and any date that a purchase was made, it would show for that particular date.I need to generate a SQL Server 2019 report showing daily purchases, including dates with zero purchases.

My current table only includes purchase dates. I need a query to generate a complete calendar of dates and join purchase details to it.

Item Date of Purchase Quantity Cost
Pepsi 2025-01-01 4 $15
Office Supplies 2025-03-31 5 $90

I found this script, but cannot get it to join on the date of purchase. Output should be:

Purchases_Table:

Date Items Cost
2025-01-01 Coke $15
2025-01-02
2025-01-03
....
2025-03-31 Office Supplies $90
2025-04-01

Code:

DECLARE @StartDate date
DECLARE @EndDate date

SELECT DATEADD(day, number, @startdate) Date
FROM master..spt_values 
WHERE type = 'P' 
  AND DATEADD(Day, number, @startdate) <= @enddate

SELECT
    Date, 
    Items, 
    Cost
FROM
    Purchases_Table pt
LEFT JOIN
    dates ON pt.Date

Please assist in figuring out how I can accomplish this.


Solution

  • Hope this helps

    DECLARE @StartDate DATE = '2025-01-01';
    DECLARE @EndDate DATE = '2025-12-31';
    
    -- Step 1: Create the calendar
    WITH Calendar AS (
        SELECT DATEADD(DAY, number, @StartDate) AS Date
        FROM master..spt_values
        WHERE type = 'P'
          AND DATEADD(DAY, number, @StartDate) <= @EndDate
    )
    
    -- Step 2: Output with all days, including where there were no purchases
    SELECT 
        c.Date,
        ISNULL(p.Items, 0) AS Items,
        ISNULL(p.Cost, 0.0) AS Cost
    FROM 
        Calendar c
    LEFT JOIN 
        Purchases_Table p ON p.Date = c.Date
    ORDER BY 
        c.Date;