KatInterview

Pivot Quarterly Crypto Sales and Yearly Totals in SQL

SQL & DataModel answer
EasyModel answerSQL & Datasqlaggregationjoins

Last 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): References coins.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:

  1. name: The coin's name.
  2. q1_amount: Total transaction amount during Quarter 1 (Jan 1 – Mar 31) of :year.
  3. q2_amount: Total transaction amount during Quarter 2 (Apr 1 – Jun 30) of :year.
  4. q3_amount: Total transaction amount during Quarter 3 (Jul 1 – Sep 30) of :year.
  5. q4_amount: Total transaction amount during Quarter 4 (Oct 1 – Dec 31) of :year.
  6. total_transactions: Total count of transactions executed for this coin in :year.
  7. total_amount: Overall sum of amount for 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 (not NULL).
  • Ensure all coins from the coins table 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?