Skip to content
Quantoros

For each account with transactions, return accountid, first transaction date, last transaction date, and the number of…

SQLLevel: IntermediateBonus drills (mixed difficulty)

For each account with transactions, return account_id, first transaction date, last transaction date, and the number of days between them (span_days).

Table definitions (from the source exercise):

CREATE TABLE transactions(transaction_id INTEGER PRIMARY KEY, account_id INTEGER, transaction_date TEXT, amount REAL, merchant_category TEXT);
Hints
  • Write an interleaving of two concurrent operations.
  • Which observations does the isolation level permit, and what happens on a mid-operation failure?

Answer

Approach: MIN, MAX, and DATEDIFF(MAX(...), MIN(...)) in one grouped query.

SELECT account_id,
       MIN(transaction_date) AS first_txn,
       MAX(transaction_date) AS last_txn,
       DATEDIFF(MAX(transaction_date), MIN(transaction_date)) AS span_days
FROM transactions
GROUP BY account_id;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions