Skip to content
Quantoros

Return the customerid of customers who have transactions in BOTH the grocery and travel categories. Table definitions…

SQLLevel: IntermediateBonus drills (mixed difficulty)

Return the customer_id of customers who have transactions in BOTH the grocery and travel categories.

Table definitions (from the source exercise):

CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
CREATE TABLE accounts(account_id INTEGER PRIMARY KEY, customer_id INTEGER, product_type TEXT, open_date TEXT, credit_limit INTEGER, status TEXT);
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: Filter to the two categories, group by customer, HAVING COUNT(DISTINCT category) = 2.

SELECT a.customer_id
FROM accounts a
JOIN transactions t ON t.account_id = a.account_id
WHERE t.merchant_category IN ('grocery', 'travel')
GROUP BY a.customer_id
HAVING COUNT(DISTINCT t.merchant_category) = 2;

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