We’re improving Formula Genius. We’re redesigning the app and fixing issues along the way. Sorry for any disruption, and thank you for your patience.
SQL intermediate

How to Aggregate Sales by Month in SQL?

Aggregating sales data by month can provide valuable insights. Use DATE_TRUNC to simplify timestamp data for monthly analysis.

Formula Genius can generate a draft from a plain-English prompt. Supported formulas can be checked with sample cases; review the coverage on the result.

The formula

Prompt

"Aggregate sales by month by truncating timestamps to the month level using DATE_TRUNC"

SQL
SELECT DATE_TRUNC('month', sale_date) AS month, SUM(amount) AS total_sales FROM sales GROUP BY month ORDER BY month;

This SQL query truncates timestamps to the month level and sums sales amounts for each month.

Step-by-step breakdown

  1. Use DATE_TRUNC to truncate the sale_date to the first day of the month.
  2. Select the truncated date as 'month' for grouping.
  3. Sum the sales amounts for each truncated month.
  4. Group the results by the truncated month to aggregate sales.

Edge cases & warnings

  • Sales data with timestamps from different time zones may yield unexpected results.
  • Months with no sales will not appear in the results unless handled explicitly.
  • Leap years may affect the aggregation if not accounted for in date handling.

Examples

Prompt

"sale_date: '2023-01-15', amount: 100"

SQL
month: '2023-01-01', total_sales: 100
Prompt

"sale_date: '2023-01-20', amount: 150; sale_date: '2023-02-10', amount: 200"

SQL
month: '2023-01-01', total_sales: 150; month: '2023-02-01', total_sales: 200

Frequently asked questions

What does DATE_TRUNC do?

DATE_TRUNC truncates a timestamp to the specified precision, such as month.

Can I use DATE_TRUNC with other time intervals?

Yes, DATE_TRUNC can truncate to various intervals like day, week, or year.

What happens if there are no sales in a month?

Months with no sales will not appear in the result set unless explicitly included.

Can't find what you need?

Describe a formula in plain English. Formula Genius drafts and explains it, and can check supported formulas on sample cases.