Foundations › SQL › Aggregation & Analysis
Aggregation & AnalysisCASE WHEN and Dates: Bucketing and Time Reports
CASE WHEN is SQL's IF: it buckets values or calculates conditionally. Combined with aggregation it becomes a powerful analysis tool.
Bucketing products by price. Open in SQL Lab
Conditional aggregation
Turning rows into columns: the SQL pivot technique. Open in SQL Lab
Dates
Orders per month. strftime extracts a part of the date in SQLite. Open in SQL Lab
Adding and subtracting days and computing differences. Open in SQL Lab
| Task | SQLite | PostgreSQL | MySQL | SQL Server |
|---|---|---|---|---|
| Month | strftime('%Y-%m', d) | to_char(d,'YYYY-MM') | DATE_FORMAT(d,'%Y-%m') | FORMAT(d,'yyyy-MM') |
| Day difference | julianday(b)-julianday(a) | b - a | DATEDIFF(b, a) | DATEDIFF(day, a, b) |
| Add 30 days | date(d,'+30 day') | d + INTERVAL '30 day' | d + INTERVAL 30 DAY | DATEADD(day,30,d) |
For advanced readers Time-report tips
Dates are where dialects differ most, so keep a cheat sheet. For monthly reports group on the first day of the month as a real date (DATE_TRUNC in PostgreSQL) for correct sorting, and join a calendar table to show months with no data.
Exercise 1 — Show the number of products per tier: under 200 'Budget', 200 to 600 'Standard', above 'Premium': tier and n.
Use CASE in SELECT then GROUP BY tier.
Exercise 2 — Show orders per month in 2026 (month as YYYY-MM and n), sorted by month.
strftime('%Y-%m', order_date) plus a WHERE for the year.
- CASE WHEN buckets and calculates conditionally.
- SUM(CASE ...) turns rows into columns.
- Date functions differ across dialects.
Want an expert to do it for you?
Gomaa Intelligence turns your data into clear reports and decisions. Tell us your problem and we will reply.