Pivot Quarterly Crypto Sales and Yearly Totals in SQL
SQL & DataModel answerLast updated
Write an efficient SQL query to aggregate quarterly activity and overall yearly stats per cryptocurrency, preserving coins with zero transactions.
You are analyzing asset volume on a trading platform. You are given two tables representing available cryptocurrencies and historical activity:
Schema
coins
coin_id(INT, Primary Key): Unique identifier for the coin.name(VARCHAR): Display name of the coin.
transactions
id(BIGINT, Primary Key): Unique transaction identifier.coin_id(INT, Foreign Key): Referencescoins.coin_id.dt(DATETIME): Timestamp of the transaction in UTC.amount(DECIMAL(18,2)): Trade value of the transaction.
Requirement
Given a parameter input :year, produce a result set containing exactly one row per registered coin in coins with the following attributes:
name: The coin's name.q1_amount: Total transactionamountduring Quarter 1 (Jan 1 – Mar 31) of:year.q2_amount: Total transactionamountduring Quarter 2 (Apr 1 – Jun 30) of:year.q3_amount: Total transactionamountduring Quarter 3 (Jul 1 – Sep 30) of:year.q4_amount: Total transactionamountduring Quarter 4 (Oct 1 – Dec 31) of:year.total_transactions: Total count of transactions executed for this coin in:year.total_amount: Overall sum ofamountfor this coin in:year.
Rules & Formatting
- If a coin has no record of transactions for a given quarter or the entire target year, the corresponding amount sums and transaction counts must be reported as
0(notNULL). - Ensure all coins from the
coinstable are listed in the final output. - Match column names and order exactly as specified.
Hints
Hint 1
Consider how filtering in a WHERE clause versus an ON clause affects the result of a LEFT JOIN when dealing with coins that have no transaction records.
Hint 2
What is the difference between using COUNT(*) and COUNT(table_alias.column) when performing conditional aggregation over a LEFT JOIN?
Hint 3
How can you make your date filtering sargable to take advantage of database indexes on timestamp columns?
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Core Logic
This problem requires conditional aggregation (pivoting rows into columns) combined with a preserved outer join to handle entities without activity.
To solve this cleanly, we need to address three key database concepts:
- Outer Join Placement: We must execute a
LEFT JOINstarting fromcoins. The filter restricting transactions to:yearmust reside inside theJOIN ... ONclause. Placing date filters in theWHEREclause converts theLEFT JOINinto anINNER JOIN, accidentally discarding coins that had zero transactions in that year. - Sargable Date Ranges: Rather than wrapping
dtinside year extraction functions likeYEAR(t.dt) = :year(which breaks index seeks), we filter using a half-open boundary range:t.dt >= 'YYYY-01-01'andt.dt < 'YYYY+1-01-01'. - Null Handling & Aggregations: When a coin has no transactions, standard aggregate functions return
NULL. We wrap aggregations withCOALESCE(..., 0)to enforce zero values. Additionally, counting total transactions requiresCOUNT(t.id)instead ofCOUNT(*), becauseCOUNT(*)counts the default single row produced by theLEFT JOINfor unmatched coins, giving a false count of1.
SQL Implementation
Standard / PostgreSQL Solution
SELECT
c.name,
COALESCE(SUM(t.amount) FILTER (WHERE EXTRACT(QUARTER FROM t.dt) = 1), 0) AS q1_amount,
COALESCE(SUM(t.amount) FILTER (WHERE EXTRACT(QUARTER FROM t.dt) = 2), 0) AS q2_amount,
COALESCE(SUM(t.amount) FILTER (WHERE EXTRACT(QUARTER FROM t.dt) = 3), 0) AS q3_amount,
COALESCE(SUM(t.amount) FILTER (WHERE EXTRACT(QUARTER FROM t.dt) = 4), 0) AS q4_amount,
COUNT(t.id) AS total_transactions,
COALESCE(SUM(t.amount), 0) AS total_amount
FROM coins c
LEFT JOIN transactions t
ON t.coin_id = c.coin_id
AND t.dt >= MAKE_DATE(:year, 1, 1)
AND t.dt < MAKE_DATE(:year + 1, 1, 1)
GROUP BY c.coin_id, c.name
ORDER BY c.name;
MySQL / Portable Solution
SELECT
c.name,
COALESCE(SUM(CASE WHEN MONTH(t.dt) BETWEEN 1 AND 3 THEN t.amount END), 0) AS q1_amount,
COALESCE(SUM(CASE WHEN MONTH(t.dt) BETWEEN 4 AND 6 THEN t.amount END), 0) AS q2_amount,
COALESCE(SUM(CASE WHEN MONTH(t.dt) BETWEEN 7 AND 9 THEN t.amount END), 0) AS q3_amount,
COALESCE(SUM(CASE WHEN MONTH(t.dt) BETWEEN 10 AND 12 THEN t.amount END), 0) AS q4_amount,
COUNT(t.id) AS total_transactions,
COALESCE(SUM(t.amount), 0) AS total_amount
FROM coins c
LEFT JOIN transactions t
ON t.coin_id = c.coin_id
AND t.dt >= MAKEDATE(:year, 1)
AND t.dt < MAKEDATE(:year + 1, 1)
GROUP BY c.coin_id, c.name
ORDER BY c.name;
Complexity & Execution Analysis
- Time Complexity:
- With an index on
transactions(coin_id, dt), the database performs a fast index range scan for each coin restricted to the target year. Total time is $\mathcal{O}(C \log N + T_{year})$, where $C$ is the number of coins, $N$ is total transaction rows, and $T_{year}$ is transactions in the target year. - Aggregation is performed in a single pass over the filtered rows in $\mathcal{O}(C + T_{year})$.
- With an index on
- Space Complexity: $\mathcal{O}(C)$ memory needed to store hash or stream aggregate state per coin.
Edge Cases & Pitfalls
| Scenario | Behavior |
|---|---|
| No activity in target year | Preserved via LEFT JOIN; COUNT(t.id) evaluates to 0 and COALESCE converts NULL sum outputs to 0.00. |
| Duplicate coin names | GROUP BY c.coin_id, c.name prevents collapsing distinct assets sharing an identical display name. |
| Sub-second precision timestamps | Half-open intervals (>= Jan 1 and < Jan 1 next year) correctly capture microsecond timestamps up to 23:59:59.999999 without missing data. |
WHERE vs ON placement | Putting dt filters in WHERE causes t.dt IS NULL check failures for inactive coins, turning the join into an inner join and omitting valid coins. |