SQL Month-to-Date

MTD's monthly counterpart to YTD — from the 1st of this month through today, same DATE_TRUNC pattern at the narrower grain.

What & Why

Month-to-date (MTD) is the same idea as YTD, scoped to the current month instead of the current year — mechanically identical to the earlier "Current Month" lesson, with the business-reporting framing that MTD implies a comparison against a prior month's equivalent point.

See How It Works

BUSINESS QUESTION

Using 2024-03-31 as a fixed report date, Marketing wants the month-to-date lead count and needs to see that the count resets when a new month begins.

idcampaign_idemailcreated_atqualified_atconverted_atlead_scoresourcecountry
3011ana@example.com2024-01-21 09:10:00+002024-01-22 11:00:00+002024-02-02 10:00:00+0086google_adsUS
3021ben@example.com2024-01-24 12:40:00+00NULLNULL52google_adsCA
3032chloe@example.com2024-02-16 08:30:00+002024-02-18 14:20:00+00NULL74emailGB
3043dev@example.com2024-03-20 17:15:00+002024-03-21 09:00:00+002024-04-04 16:00:00+0091linkedinUS
Watch the month-to-date count reset at a new monthStep 1 of 2
2024-03-01 <= created_at < 2024-04-01
as_of_datemtd_leads
2024-03-311

As of March 31, Lead 304 is the one marketing.leads row inside March month-to-date.

EXAMPLE QUERY
SELECT
  DATE '2024-03-31' AS as_of_date,
  COUNT(*) AS mtd_leads
FROM marketing.leads
WHERE created_at >= TIMESTAMPTZ '2024-03-01 00:00:00+00'
  AND created_at < TIMESTAMPTZ '2024-04-01 00:00:00+00';
Now You Try

Practice this concept

Using 2024-03-31 as the fixed report date, Marketing wants the month-to-date lead count.

Available schema
marketing

Prefix tables with marketing.table_name.

as_of_datemtd_leads
marketing.leads
ColumnType
idinteger
campaign_idinteger
emailtext
created_attimestamp with time zone
qualified_attimestamp with time zone
converted_attimestamp with time zone
lead_scoreinteger
sourcetext
countrytext
archive_statustext
query.sql
Intermediate business practice

Sign up free to try it on a real business scenario