Quarterly and Annual Transaction Breakdown by Coin
Easy · Data Manipulation (SQL/Python) · Data Scientist · Online Assessment
Problem Statement
You are given a reference table coins listing digital assets and a ledger table transactions recording individual UTC transfers.
For calendar year 2024 (:year = 2024 in the SQLite evaluation environment), write a SQL query (SQLite dialect) that outputs one summary row for every coin in coins with quarterly and full-year totals:
- Quarterly sums (
2024UTC): Bucket each2024transaction by its UTC calendar quarter fromdt:q1_amount: sum ofamountin Q1 (January–March2024)q2_amount: sum ofamountin Q2 (April–June2024)q3_amount: sum ofamountin Q3 (July–September2024)q4_amount: sum ofamountin Q4 (October–December2024)
- Annual count and total (
2024UTC):total_transactions: total count of2024transactions for that coin.total_amount: total sum ofamountacross all2024transactions for that coin.
- Zero-activity coins and edge cases:
- Every coin in
coinsmust appear in the result, even if it has zero transactions in2024(or only transactions in other years); report0rather thanNULLfor empty counts and sums. - Group at the
coin_idgrain so two distinct coins with the samenamestay separate rows. - A
2024transaction whoseamountisNULLstill counts as1towardtotal_transactionswhile contributing0to sums.
- Every coin in
Return columns in this exact order: name, q1_amount, q2_amount, q3_amount, q4_amount, total_transactions, total_amount.
Input Schema
coins
| Column | Type | Description |
|---|---|---|
coin_id |
INTEGER |
Primary key identifying the coin |
name |
VARCHAR |
Display name of the coin |
transactions
| Column | Type | Description |
|---|---|---|
id |
BIGINT |
Primary key identifying the transaction |
coin_id |
INTEGER |
Identifier referencing coins.coin_id |
dt |
TIMESTAMP |
UTC timestamp of the transaction ('YYYY-MM-DD HH:MM:SS') |
amount |
DECIMAL(18,2) |
Transaction value (may be zero, negative, or NULL) |
Examples
Example 1
Input:
coins
| coin_id | name |
|---|---|
| 10 | Avalanche |
| 20 | Cardano |
| 30 | Polkadot |
| 40 | Cosmos |
transactions
| id | coin_id | dt | amount |
|---|---|---|---|
| 501 | 10 | 2024-01-08 09:30:00 | 600 |
| 502 | 10 | 2024-03-19 15:45:00 | 140.25 |
| 503 | 10 | 2024-06-12 11:00:00 | 310 |
| 504 | 10 | 2024-10-25 20:15:00 | 490.5 |
| 505 | 20 | 2023-12-31 23:59:59 | 850 |
| 506 | 20 | 2024-05-03 07:20:00 | 225.5 |
| 507 | 20 | 2024-12-31 22:10:00 | 174.5 |
| 508 | 30 | 2024-07-01 00:00:00 | 45 |
| 509 | 30 | 2024-09-30 23:59:59 | 55.75 |
Output:
| name | q1_amount | q2_amount | q3_amount | q4_amount | total_transactions | total_amount |
|---|---|---|---|---|---|---|
| Avalanche | 740.25 | 310 | 0 | 490.5 | 4 | 1540.75 |
| Cardano | 0 | 225.5 | 0 | 174.5 | 2 | 400 |
| Polkadot | 0 | 0 | 100.75 | 0 | 2 | 100.75 |
| Cosmos | 0 | 0 | 0 | 0 | 0 | 0 |
Explanation:
- Avalanche (coin_id = 10) has two Q1 transfers (600 + 140.25 = 740.25), one Q2 transfer (310), zero in Q3, and one Q4 transfer (490.5), totaling 4 transfers and 1540.75.
- Cardano (coin_id = 20) ignores transfer 505 from 2023-12-31 23:59:59 and includes both its May transfer (225.5 in Q2) and its late New Year's Eve transfer 507 (174.5 in Q4), totaling 2 transfers and 400.
- Polkadot (coin_id = 30) has transfers on the exact first and last seconds of Q3 (45 + 55.75 = 100.75).
- Cosmos (coin_id = 40) has no 2024 rows and still appears with 0 across every numeric column.
Constraints
- Target year is
2024UTC ('2024-01-01 00:00:00' <= dt < '2025-01-01 00:00:00'). coin_iduniquely identifies rows incoins, whilenameis not guaranteed to be unique.- Ignore any row in
transactionswhosecoin_idis absent fromcoins. - Output rows may be returned in any order.
Step-by-step walkthrough
Understand the goal and rules
We are given two tables:
coins(coin_id, name): master list of coins (coin_idis the primary key).transactions(id, coin_id, dt, amount): individual UTC transactions (idis the primary key).
For a target calendar year
:year(the test suite runs plain SQL without bound parameters and specifies:year = 2024), we must output one row per coin with seven columns:name | q1_amount | q2_amount | q3_amount | q4_amount | total_transactions | total_amountThree requirements shape the query:
- Quarters: Q1 = Jan–Mar, Q2 = Apr–Jun, Q3 = Jul–Sep, Q4 = Oct–Dec of
2024. - Every coin appears: coins with zero transactions in
2024(whether they have no transactions ever, or only transactions in other years like2023) must still appear with0for every count and sum — neverNULL. - Output order: rows can be returned in any order.
Key idea: conditional aggregation in a single pass
A beginner's first instinct is often to write four separate
GROUP BYsubqueries — one for Q1, one for Q2, one for Q3, and one for Q4 — and join all four back tocoins. That works, but it scanstransactionsrepeatedly and repeats the same boilerplate four times.Instead, we can pivot quarters into columns in one pass using conditional aggregation — placing a
CASE WHEN ... THEN amount ELSE 0 ENDfilter insideSUM(...):SUM(CASE WHEN y.quarter = 1 THEN y.amount ELSE 0 END) AS q1_amountAs SQL walks through a coin's 2024 transactions, this
CASEexpression contributesamountfor Q1 rows and0for Q2/Q3/Q4 rows. Four side-by-sideSUM(CASE ...)expressions compute all four quarters in the sameGROUP BYpass that computestotal_transactionsandtotal_amount.To keep inactive coins intact, we pair conditional aggregation with two structural choices: 1. Pre-filter
transactionsto2024inside a Common Table Expression (CTE) (WITH year_tx AS (...)) before joining. 2. StartFROM coinsandLEFT JOIN year_tx.Step 1: Filter 2024 transactions and compute the quarter
Inside the
year_txCTE, we prepare only the 2024 transactions:- Half-open timestamp range (
dt >= '2024-01-01' AND dt < '2025-01-01'): never writedt BETWEEN '2024-01-01' AND '2024-12-31'on aDATETIME/TIMESTAMPcolumn!'2024-12-31'means midnight at the start of December 31 (00:00:00), which silently drops every transaction later that day (like2024-12-31 22:10:00). Using< '2025-01-01'includes every second up through2024-12-31 23:59:59, and comparing rawdtwithout wrapping it in a function lets the database use an index ondt. - Month-to-quarter integer math: SQLite has no built-in
QUARTER(dt)function (unlike PostgreSQL'sEXTRACT(QUARTER FROM dt)or MySQL'sQUARTER(dt)). Extracting the month1..12viaCAST(strftime('%m', dt) AS INTEGER)and computing(month + 2) / 3using integer division maps every month to its exact quarter1..4:
month m: 1 2 3 | 4 5 6 | 7 8 9 | 10 11 12 (m + 2): 3 4 5 | 6 7 8 | 9 10 11 | 12 13 14 (m + 2) / 3: 1 1 1 | 2 2 2 | 3 3 3 | 4 4 4COALESCE(amount, 0):amountis nullable in the schema. Turning aNULLamount into0ensures the row still counts as a transaction while contributing0rather than poisoning a quarter's sum withNULL.
WITH year_tx AS ( -- Filter transactions to :year = 2024 BEFORE joining so inactive coins stay intact, -- turn NULL amounts into 0, and map months 1..12 to quarters 1..4 via integer math. SELECT id, coin_id, COALESCE(amount, 0) AS amount, (CAST(strftime('%m', dt) AS INTEGER) + 2) / 3 AS quarter FROM transactions WHERE dt >= '2024-01-01' AND dt < '2025-01-01' )(In parameterized application code, replace the two string literals with
:year_startand:next_year_start, or in PostgreSQLmake_date(:year, 1, 1)andmake_date(:year + 1, 1, 1).)- Half-open timestamp range (
Step 2: Drive from coins with LEFT JOIN and group by coin_id
Because every coin must appear in the output,
coinsgoes on the left side of aLEFT JOIN:coins year_tx (2024 only) Result of LEFT JOIN ----- ------------------- ------------------- 10 | Avalanche --> 2 rows in Q1, 1 Q2, 1 Q4 4 matched rows for Avalanche 20 | Cardano --> 1 row Q2, 1 Q4 (2023 gone) 2 matched rows for Cardano 40 | Cosmos --> (no matching 2024 rows) 1 row: (40, 'Cosmos', id=NULL, amount=NULL, quarter=NULL)Notice two crucial details here:
- Why the
2024filter had to happen before theLEFT JOIN: if you joinedcoinsdirectly to rawtransactionsand wroteWHERE t.dt >= '2024-01-01'at the bottom of the query,Cosmos's paddedt.dt = NULLrow would failWHEREandCosmoswould vanish! - Why we write
GROUP BY c.coin_id, c.nameinstead ofGROUP BY c.name:coin_idis the primary key, notname. If two different coins both happen to be named'Wrapped', grouping byc.coin_id, c.namekeeps them as two separate rows instead of merging their money together.
- Why the
Step 3: Build the quarterly columns and safe zeros
Now look at how each aggregate behaves on both matched rows and an inactive coin's single
NULL-padded row:SUM(CASE WHEN y.quarter = 1 THEN y.amount ELSE 0 END): for an inactive coin,y.quarterisNULL, soWHEN y.quarter = 1is not true,CASEfalls through toELSE 0, andSUM(0)cleanly returns0!COUNT(y.id)(notCOUNT(*)!):COUNT(*)counts rows, so forCosmos's singleNULL-paddedLEFT JOINrow,COUNT(*)returns1instead of0!COUNT(y.id)counts only non-NULLvalues ofy.id: sinceidis the primary key oftransactions, it is non-NULLon every real 2024 transaction (even one whoseamountwasNULL) andNULLon an inactive coin's padded row, giving0forCosmos.COALESCE(SUM(y.amount), 0): forCosmos,y.amountisNULL, andSUMover all-NULLinputs returnsNULL. WrappingSUM(y.amount)inCOALESCE(..., 0)turns thatNULLinto0.
SELECT c.name, SUM(CASE WHEN y.quarter = 1 THEN y.amount ELSE 0 END) AS q1_amount, SUM(CASE WHEN y.quarter = 2 THEN y.amount ELSE 0 END) AS q2_amount, SUM(CASE WHEN y.quarter = 3 THEN y.amount ELSE 0 END) AS q3_amount, SUM(CASE WHEN y.quarter = 4 THEN y.amount ELSE 0 END) AS q4_amount, -- Count y.id (non-NULL key) rather than * so an unmatched LEFT JOIN row counts as 0. COUNT(y.id) AS total_transactions, COALESCE(SUM(y.amount), 0) AS total_amount FROM coins AS c LEFT JOIN year_tx AS y ON y.coin_id = c.coin_id GROUP BY c.coin_id, c.nameTrace Example 1 step by step
First,
year_txdrops transaction505(2023-12-31 23:59:59, wrong year) and tags the remaining 8 rows with quarters:id | coin_id | dt | amount | month | quarter ----+---------+---------------------+--------+-------+-------- 501 | 10 | 2024-01-08 09:30:00 | 600 | 1 | 1 502 | 10 | 2024-03-19 15:45:00 | 140.25 | 3 | 1 503 | 10 | 2024-06-12 11:00:00 | 310 | 6 | 2 504 | 10 | 2024-10-25 20:15:00 | 490.5 | 10 | 4 506 | 20 | 2024-05-03 07:20:00 | 225.5 | 5 | 2 507 | 20 | 2024-12-31 22:10:00 | 174.5 | 12 | 4 (late on Dec 31) 508 | 30 | 2024-07-01 00:00:00 | 45 | 7 | 3 (1st second of Q3) 509 | 30 | 2024-09-30 23:59:59 | 55.75 | 9 | 3 (last second of Q3)Joining onto
coins(10=Avalanche, 20=Cardano, 30=Polkadot, 40=Cosmos) and grouping produces:name | q1_amount | q2_amount | q3_amount | q4_amount | total_transactions | total_amount ----------+-----------+-----------+-----------+-----------+--------------------+------------- Avalanche | 740.25 | 310 | 0 | 490.5 | 4 | 1540.75 Cardano | 0 | 225.5 | 0 | 174.5 | 2 | 400 Polkadot | 0 | 0 | 100.75 | 0 | 2 | 100.75 Cosmos | 0 | 0 | 0 | 0 | 0 | 0Full SQL solution
Putting the CTE and the outer conditional aggregation together gives the complete query:
WITH year_tx AS ( -- Filter transactions to :year = 2024 BEFORE joining so inactive coins stay intact, -- turn NULL amounts into 0, and map months 1..12 to quarters 1..4 via integer math. SELECT id, coin_id, COALESCE(amount, 0) AS amount, (CAST(strftime('%m', dt) AS INTEGER) + 2) / 3 AS quarter FROM transactions WHERE dt >= '2024-01-01' AND dt < '2025-01-01' ) -- Start from coins and LEFT JOIN so coins with zero 2024 activity still produce a row; -- group by coin_id (primary key) so two coins sharing the same name never merge. SELECT c.name, SUM(CASE WHEN y.quarter = 1 THEN y.amount ELSE 0 END) AS q1_amount, SUM(CASE WHEN y.quarter = 2 THEN y.amount ELSE 0 END) AS q2_amount, SUM(CASE WHEN y.quarter = 3 THEN y.amount ELSE 0 END) AS q3_amount, SUM(CASE WHEN y.quarter = 4 THEN y.amount ELSE 0 END) AS q4_amount, -- Count y.id (non-NULL key) rather than * so an unmatched LEFT JOIN row counts as 0. COUNT(y.id) AS total_transactions, COALESCE(SUM(y.amount), 0) AS total_amount FROM coins AS c LEFT JOIN year_tx AS y ON y.coin_id = c.coin_id GROUP BY c.coin_id, c.name✅ Submit now — all tests should pass.
Intuition & how it works
Picture preparing an annual summary sheet that lists every registered coin down the left margin — even coins that had zero trades all year — with four columns for Q1 through Q4, a trade counter, and a yearly total. First, you pull only the 2024 receipts out of the filing cabinet and stamp Q1, Q2, Q3, or Q4 on each receipt according to its month. Next, you go down the master list of coins, attach each coin's 2024 receipts (leaving idle coins with an empty clip), and add each receipt's dollar amount into the calculator for its stamped quarter!
Writing FROM transactions JOIN coins fails immediately because coins with zero 2024 activity (like Cosmos in Example 1) have no transaction rows and disappear from the output. Even with FROM coins LEFT JOIN transactions, filtering the year in an outer WHERE dt >= '2024-01-01' fails because an idle coin's dt is NULL, which fails the WHERE check and deletes the coin anyway, while COUNT(*) wrongly counts that single NULL placeholder row as 1 transaction. Instead, we pre-filter 2024 rows inside a Common Table Expression (CTE) (a named temporary query step written with WITH) using a half-open interval (>= start AND < end, which includes every timestamp up to midnight of the next year), LEFT JOIN that filtered set onto coins, use conditional aggregation (SUM(CASE WHEN ... END) inside GROUP BY) to route each receipt into q1_amount–q4_amount, count non-NULL transaction keys with COUNT(y.id), and wrap nullable sums with COALESCE (a SQL function that returns its first non-NULL argument, turning NULL into 0).
Here is a tiny 3-coin trace showing active, wrong-year, and completely idle coins:
coins: (10, 'AVAX'), (20, 'ADA'), (40, 'ATOM')
transactions: AVAX has $200 in Jan 2024 & $80 in Jun 2024; ADA has $850 in Dec 2023; ATOM has none.
1. year_tx (2024 only): keeps AVAX ($200 -> Q1, $80 -> Q2); drops ADA's 2023 row.
2. coins LEFT JOIN year_tx:
- AVAX -> 2 matched rows -> Q1=200, Q2=80, Q3=0, Q4=0, count=2, total=280
- ADA -> 1 NULL-padded -> Q1=0, Q2=0, Q3=0, Q4=0, count=0, total=0
- ATOM -> 1 NULL-padded -> Q1=0, Q2=0, Q3=0, Q4=0, count=0, total=0
Complexity
Let C be the number of rows in coins, T be the total number of rows in transactions, and Y be the number of transactions falling inside :year (2024).
- Time — O(C + Y) with an index on
dt(or O(C + T) without an index): Whentransactions(dt)is indexed, the range filterdt >= '2024-01-01' AND dt < '2025-01-01'seeks directly to the start of2024and scans only the Y rows of that year (plus O(log T) for the initial B-tree seek); without an index, the database scans all T rows once. Joining the C coins to the Y filtered rows and grouping by(c.coin_id, c.name)takes O(C + Y) time using hash join and hash aggregation (or O((C + Y) log(C + Y)) if the engine chooses sort-merge). - Space — O(C): Hash aggregation maintains one accumulator entry (six numeric counters plus
name) for each of the C coins, plus up to O(Y) if the engine materializesyear_txrather than streaming it.
Indexes that help: An index on transactions(dt) (or transactions(dt, coin_id, amount)) serves the year filter directly because dt >= '2024-01-01' AND dt < '2025-01-01' is a sargable predicate (a filter written on a bare column rather than strftime('%Y', dt) = '2024', allowing the database to jump straight into a B-tree index instead of running a function on every row in the table).
Edge cases
- Coin with no transactions ever:
LEFT JOINproduces oneNULL-padded row,ELSE 0andCOALESCEturn all five sums into0, andCOUNT(y.id)returns0. - Coin with transactions only outside
2024:year_txfilters out non-2024rows before theLEFT JOIN, so the coin still appears with all0s. - Exact year and quarter timestamp boundaries:
2024-01-01 00:00:00and2024-12-31 23:59:59are included, while2023-12-31 23:59:59and2025-01-01 00:00:00are excluded; likewise, the first and last second of every quarter map to that quarter (1..4). - Two coins sharing the same
name:GROUP BY c.coin_id, c.namekeeps distinctcoin_ids as separate output rows instead of merging them. - Zero and negative amounts: still count toward
total_transactions(idis non-NULL) and add/subtract normally in the sums. NULLtransactionamount:COALESCE(amount, 0)insideyear_txensures aNULL-amount row still counts intotal_transactions(COUNT(y.id)) while adding0instead of turning a single-row quarter sum intoNULL.- SQLite binary floating-point storage: SQLite stores
DECIMAL(18,2)values as IEEE-754 floats (REAL), so adding100.1 + 0.2can yield100.30000000000001in raw SQLite (whereas PostgreSQL and MySQLDECIMALarithmetic is exact base-10).
Common mistakes
- Using an inner
JOIN(or startingFROM transactions): drops every coin that had zero transactions in2024. - Putting
WHERE dt >= '2024-01-01'in the outer query afterLEFT JOIN: rejects theNULLrow produced for inactive coins, silently turning theLEFT JOINback into an inner join. - Writing
COUNT(*)instead ofCOUNT(y.id): reportstotal_transactions = 1for coins with zero activity becauseCOUNT(*)counts the singleNULL-paddedLEFT JOINrow (andCOUNT(y.amount)has the opposite bug if a real transaction hasamount IS NULL). - Omitting
ELSE 0orCOALESCE(..., 0): causes empty quarters or inactive coins'total_amountto returnNULLinstead of0. - Using
BETWEEN '2024-01-01' AND '2024-12-31'on timestamps: excludes every transaction after2024-12-31 00:00:00on New Year's Eve. - Off-by-one integer quarter formula (
month / 3): maps January and February to0and March to1; always use(month + 2) / 3or(month - 1) / 3 + 1. - Comparing
strftime('%Y', dt) = 2024in SQLite:strftimereturns text ('2024'), and comparing text to an integer2024with no type affinity is always false in SQLite!
Follow-up questions
- How would you generalize this report across multiple calendar years while still guaranteeing a zero-filled row for every (coin, year) combination? Build a small
yearstable (usingVALUES (2023), (2024)or a recursive date series),CROSS JOINcoinswithyearsto create the complete(coin, year)grid, andLEFT JOINpre-aggregated or year-tagged transactions on bothcoin_idandyr. On Example 1, this outputs 8 rows (4 coins × 2 years), showing Cardano's2023Q4 transaction (850) on its2023row and zeros for idle(coin, year)pairs.
sql
WITH years(yr) AS (
VALUES (2023), (2024)
),
tx AS (
SELECT
id,
coin_id,
COALESCE(amount, 0) AS amount,
CAST(strftime('%Y', dt) AS INTEGER) AS yr,
(CAST(strftime('%m', dt) AS INTEGER) + 2) / 3 AS quarter
FROM transactions
WHERE dt >= '2023-01-01'
AND dt < '2025-01-01'
)
SELECT
c.name,
y.yr AS year,
SUM(CASE WHEN t.quarter = 1 THEN t.amount ELSE 0 END) AS q1_amount,
SUM(CASE WHEN t.quarter = 2 THEN t.amount ELSE 0 END) AS q2_amount,
SUM(CASE WHEN t.quarter = 3 THEN t.amount ELSE 0 END) AS q3_amount,
SUM(CASE WHEN t.quarter = 4 THEN t.amount ELSE 0 END) AS q4_amount,
COUNT(t.id) AS total_transactions,
COALESCE(SUM(t.amount), 0) AS total_amount
FROM coins AS c
CROSS JOIN years AS y
LEFT JOIN tx AS t
ON t.coin_id = c.coin_id
AND t.yr = y.yr
GROUP BY c.coin_id, c.name, y.yr
-
If transaction timestamps are stored in UTC but quarters must follow a local time zone such as 'America/New_York', how should the filter and quarter calculation change? A timestamp near a boundary like
2024-04-01 02:00:00UTC is actually2024-03-31 22:00:00EDT (still Q1, not Q2!), so both the year filter and the quarter extraction must use local wall-clock time. In PostgreSQL, extract the quarter from(dt AT TIME ZONE 'UTC') AT TIME ZONE 'America/New_York', and to keeptransactions(dt)index-friendly (sargable), convert the two local year boundaries (2024-01-01 00:00:00and2025-01-01 00:00:00in'America/New_York') into UTC timestamps for theWHERE dt >= ... AND dt < ...filter. -
How would you return the report in long format — one row per (coin, quarter) with four rows per coin — instead of four separate quarter columns? Charting tools and BI dashboards often prefer long format (
name, quarter, total_transactions, quarter_amount).CROSS JOINcoinswithVALUES (1), (2), (3), (4)so every coin gets all four quarter slots even when empty, thenLEFT JOIN year_txon bothcoin_idandquarter, producing4 × 4 = 16rows on Example 1.
sql
WITH quarters(quarter) AS (
VALUES (1), (2), (3), (4)
),
year_tx AS (
SELECT
id,
coin_id,
COALESCE(amount, 0) AS amount,
(CAST(strftime('%m', dt) AS INTEGER) + 2) / 3 AS quarter
FROM transactions
WHERE dt >= '2024-01-01'
AND dt < '2025-01-01'
)
SELECT
c.name,
q.quarter,
COUNT(y.id) AS total_transactions,
COALESCE(SUM(y.amount), 0) AS quarter_amount
FROM coins AS c
CROSS JOIN quarters AS q
LEFT JOIN year_tx AS y
ON y.coin_id = c.coin_id
AND y.quarter = q.quarter
GROUP BY c.coin_id, c.name, q.quarter
Follow-up questions
- How would you generalize this report across multiple calendar years while still guaranteeing a zero-filled row for every (coin, year) combination?
- If transaction timestamps are stored in UTC but quarters must follow a local time zone such as 'America/New_York', how should the filter and quarter calculation change?
- How would you return the report in long format — one row per (coin, quarter) with four rows per coin — instead of four separate quarter columns?
Similar questions
- Upward K-Step Tree Queries with Root Clamping
- K-th Ancestor Queries on a Tree
- Quarterly 2023 Revenue Query and Largest-File Shell Script
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages