Gomaa Intelligence.Data Hub
عربي

Foundations › SQL › Aggregation & Analysis

Aggregation & Analysis

CASE WHEN and Dates: Bucketing and Time Reports

Lesson 11 / 14· 10 min

CASE WHEN is SQL's IF: it buckets values or calculates conditionally. Combined with aggregation it becomes a powerful analysis tool.

▶ Try it yourself

Bucketing products by price. Open in SQL Lab

Conditional aggregation

▶ Try it yourself

Turning rows into columns: the SQL pivot technique. Open in SQL Lab

Dates

▶ Try it yourself

Orders per month. strftime extracts a part of the date in SQLite. Open in SQL Lab

▶ Try it yourself

Adding and subtracting days and computing differences. Open in SQL Lab

TaskSQLitePostgreSQLMySQLSQL Server
Monthstrftime('%Y-%m', d)to_char(d,'YYYY-MM')DATE_FORMAT(d,'%Y-%m')FORMAT(d,'yyyy-MM')
Day differencejulianday(b)-julianday(a)b - aDATEDIFF(b, a)DATEDIFF(day, a, b)
Add 30 daysdate(d,'+30 day')d + INTERVAL '30 day'd + INTERVAL 30 DAYDATEADD(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.

Exercise 2 — Show orders per month in 2026 (month as YYYY-MM and n), sorted by month.

Summary
  • 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.

Get your data analyzed by an expert ↗