Skip to content

Date and Time Analytics in SQL

Most analytics dashboards are time-based:

  • Daily Active Users (DAU)
  • Weekly revenue
  • Monthly churn

Different databases have slightly different date functions.

We’ll use common patterns:

  • DATE(timestamp) to extract date
  • Group by date/week/month
Daily orders
SELECT
  DATE(order_ts) AS day,
  COUNT(*) AS orders,
  SUM(amount) AS revenue
FROM orders
GROUP BY DATE(order_ts)
ORDER BY day;
7-day rolling revenue
SELECT
  day,
  revenue,
  AVG(revenue) OVER (ORDER BY day ROWS BETWEEN 6 PRECEDING AND CURRENT ROW) AS rev_ma7
FROM (
  SELECT DATE(order_ts) AS day, SUM(amount) AS revenue
  FROM orders
  GROUP BY DATE(order_ts)
) t
ORDER BY day;
  • Time zones (UTC vs local)
  • Partial days (data ingestion delays)
  • Week definition (Mon-Sun vs Sun-Sat)

The pipeline behind every time-series metric

Section titled “The pipeline behind every time-series metric”

Whether you’re building DAU, weekly revenue, or a 7-day moving average, the pipeline is always the same three steps: truncate a precise timestamp down to the bucket you care about, group by that bucket, then optionally smooth the result with a window function.

diagram Time-bucketing pipeline mermaid
A precise timestamp is truncated to a bucket (day/week/month), grouped, and optionally smoothed with a window function.

Exercise 1 – Truncate a timestamp to a day

Section titled “Exercise 1 – Truncate a timestamp to a day”

Exercise 2 – Daily revenue with GROUP BY

Section titled “Exercise 2 – Daily revenue with GROUP BY”

SQL from Python (pandas + sqlite3) shows how to run these same queries from a script and load the results straight into a DataFrame for further analysis.

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading