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:

  1. Quarterly sums (2024 UTC): Bucket each 2024 transaction by its UTC calendar quarter from dt:
    • q1_amount: sum of amount in Q1 (January–March 2024)
    • q2_amount: sum of amount in Q2 (April–June 2024)
    • q3_amount: sum of amount in Q3 (July–September 2024)
    • q4_amount: sum of amount in Q4 (October–December 2024)
  2. Annual count and total (2024 UTC):
    • total_transactions: total count of 2024 transactions for that coin.
    • total_amount: total sum of amount across all 2024 transactions for that coin.
  3. Zero-activity coins and edge cases:
    • Every coin in coins must appear in the result, even if it has zero transactions in 2024 (or only transactions in other years); report 0 rather than NULL for empty counts and sums.
    • Group at the coin_id grain so two distinct coins with the same name stay separate rows.
    • A 2024 transaction whose amount is NULL still counts as 1 toward total_transactions while contributing 0 to sums.

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 2024 UTC ('2024-01-01 00:00:00' <= dt < '2025-01-01 00:00:00').
  • coin_id uniquely identifies rows in coins, while name is not guaranteed to be unique.
  • Ignore any row in transactions whose coin_id is absent from coins.
  • Output rows may be returned in any order.

Step-by-step walkthrough

  1. Understand the goal and rules

    We are given two tables:

    • coins(coin_id, name): master list of coins (coin_id is the primary key).
    • transactions(id, coin_id, dt, amount): individual UTC transactions (id is 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_amount
    

    Three 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 like 2023) must still appear with 0 for every count and sum — never NULL.
    • Output order: rows can be returned in any order.
  2. Key idea: conditional aggregation in a single pass

    A beginner's first instinct is often to write four separate GROUP BY subqueries — one for Q1, one for Q2, one for Q3, and one for Q4 — and join all four back to coins. That works, but it scans transactions repeatedly 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 END filter inside SUM(...):

    SUM(CASE WHEN y.quarter = 1 THEN y.amount ELSE 0 END) AS q1_amount
    

    As SQL walks through a coin's 2024 transactions, this CASE expression contributes amount for Q1 rows and 0 for Q2/Q3/Q4 rows. Four side-by-side SUM(CASE ...) expressions compute all four quarters in the same GROUP BY pass that computes total_transactions and total_amount.

    To keep inactive coins intact, we pair conditional aggregation with two structural choices: 1. Pre-filter transactions to 2024 inside a Common Table Expression (CTE) (WITH year_tx AS (...)) before joining. 2. Start FROM coins and LEFT JOIN year_tx.

  3. Step 1: Filter 2024 transactions and compute the quarter

    Inside the year_tx CTE, we prepare only the 2024 transactions:

    • Half-open timestamp range (dt >= '2024-01-01' AND dt < '2025-01-01'): never write dt BETWEEN '2024-01-01' AND '2024-12-31' on a DATETIME/TIMESTAMP column! '2024-12-31' means midnight at the start of December 31 (00:00:00), which silently drops every transaction later that day (like 2024-12-31 22:10:00). Using < '2025-01-01' includes every second up through 2024-12-31 23:59:59, and comparing raw dt without wrapping it in a function lets the database use an index on dt.
    • Month-to-quarter integer math: SQLite has no built-in QUARTER(dt) function (unlike PostgreSQL's EXTRACT(QUARTER FROM dt) or MySQL's QUARTER(dt)). Extracting the month 1..12 via CAST(strftime('%m', dt) AS INTEGER) and computing (month + 2) / 3 using integer division maps every month to its exact quarter 1..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  4
    
    • COALESCE(amount, 0): amount is nullable in the schema. Turning a NULL amount into 0 ensures the row still counts as a transaction while contributing 0 rather than poisoning a quarter's sum with NULL.
    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_start and :next_year_start, or in PostgreSQL make_date(:year, 1, 1) and make_date(:year + 1, 1, 1).)

  4. Step 2: Drive from coins with LEFT JOIN and group by coin_id

    Because every coin must appear in the output, coins goes on the left side of a LEFT 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 2024 filter had to happen before the LEFT JOIN: if you joined coins directly to raw transactions and wrote WHERE t.dt >= '2024-01-01' at the bottom of the query, Cosmos's padded t.dt = NULL row would fail WHERE and Cosmos would vanish!
    • Why we write GROUP BY c.coin_id, c.name instead of GROUP BY c.name: coin_id is the primary key, not name. If two different coins both happen to be named 'Wrapped', grouping by c.coin_id, c.name keeps them as two separate rows instead of merging their money together.
  5. 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.quarter is NULL, so WHEN y.quarter = 1 is not true, CASE falls through to ELSE 0, and SUM(0) cleanly returns 0!
    • COUNT(y.id) (not COUNT(*)!): COUNT(*) counts rows, so for Cosmos's single NULL-padded LEFT JOIN row, COUNT(*) returns 1 instead of 0! COUNT(y.id) counts only non-NULL values of y.id: since id is the primary key of transactions, it is non-NULL on every real 2024 transaction (even one whose amount was NULL) and NULL on an inactive coin's padded row, giving 0 for Cosmos.
    • COALESCE(SUM(y.amount), 0): for Cosmos, y.amount is NULL, and SUM over all-NULL inputs returns NULL. Wrapping SUM(y.amount) in COALESCE(..., 0) turns that NULL into 0.
    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
    
  6. Trace Example 1 step by step

    First, year_tx drops transaction 505 (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                  | 0
    
  7. Full 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): When transactions(dt) is indexed, the range filter dt >= '2024-01-01' AND dt < '2025-01-01' seeks directly to the start of 2024 and 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 materializes year_tx rather 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 JOIN produces one NULL-padded row, ELSE 0 and COALESCE turn all five sums into 0, and COUNT(y.id) returns 0.
  • Coin with transactions only outside 2024: year_tx filters out non-2024 rows before the LEFT JOIN, so the coin still appears with all 0s.
  • Exact year and quarter timestamp boundaries: 2024-01-01 00:00:00 and 2024-12-31 23:59:59 are included, while 2023-12-31 23:59:59 and 2025-01-01 00:00:00 are 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.name keeps distinct coin_ids as separate output rows instead of merging them.
  • Zero and negative amounts: still count toward total_transactions (id is non-NULL) and add/subtract normally in the sums.
  • NULL transaction amount: COALESCE(amount, 0) inside year_tx ensures a NULL-amount row still counts in total_transactions (COUNT(y.id)) while adding 0 instead of turning a single-row quarter sum into NULL.
  • SQLite binary floating-point storage: SQLite stores DECIMAL(18,2) values as IEEE-754 floats (REAL), so adding 100.1 + 0.2 can yield 100.30000000000001 in raw SQLite (whereas PostgreSQL and MySQL DECIMAL arithmetic is exact base-10).

Common mistakes

  • Using an inner JOIN (or starting FROM transactions): drops every coin that had zero transactions in 2024.
  • Putting WHERE dt >= '2024-01-01' in the outer query after LEFT JOIN: rejects the NULL row produced for inactive coins, silently turning the LEFT JOIN back into an inner join.
  • Writing COUNT(*) instead of COUNT(y.id): reports total_transactions = 1 for coins with zero activity because COUNT(*) counts the single NULL-padded LEFT JOIN row (and COUNT(y.amount) has the opposite bug if a real transaction has amount IS NULL).
  • Omitting ELSE 0 or COALESCE(..., 0): causes empty quarters or inactive coins' total_amount to return NULL instead of 0.
  • Using BETWEEN '2024-01-01' AND '2024-12-31' on timestamps: excludes every transaction after 2024-12-31 00:00:00 on New Year's Eve.
  • Off-by-one integer quarter formula (month / 3): maps January and February to 0 and March to 1; always use (month + 2) / 3 or (month - 1) / 3 + 1.
  • Comparing strftime('%Y', dt) = 2024 in SQLite: strftime returns text ('2024'), and comparing text to an integer 2024 with 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 years table (using VALUES (2023), (2024) or a recursive date series), CROSS JOIN coins with years to create the complete (coin, year) grid, and LEFT JOIN pre-aggregated or year-tagged transactions on both coin_id and yr. On Example 1, this outputs 8 rows (4 coins × 2 years), showing Cardano's 2023 Q4 transaction (850) on its 2023 row 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:00 UTC is actually 2024-03-31 22:00:00 EDT (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 keep transactions(dt) index-friendly (sargable), convert the two local year boundaries (2024-01-01 00:00:00 and 2025-01-01 00:00:00 in 'America/New_York') into UTC timestamps for the WHERE 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 JOIN coins with VALUES (1), (2), (3), (4) so every coin gets all four quarter slots even when empty, then LEFT JOIN year_tx on both coin_id and quarter, producing 4 × 4 = 16 rows 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

Similar questions

More Others interview questions

All 4 Others questions →