Skip to content
Quantoros

Return customerid, productid, orderdate where the same customer bought the same product in MORE than one order on the…

SQLLevel: IntermediateDuplicates and data quality

Return customer_id, product_id, order_date where the same customer bought the same product in MORE than one order on the same date.

Table definitions (from the source exercise):

CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
CREATE TABLE order_items(item_id INTEGER PRIMARY KEY, order_id INTEGER, product_id INTEGER, quantity INTEGER);
Hints
  • Define one output row and the source-table keys.
  • Check duplicates, NULLs and the order of filtering and aggregation.

Answer

Approach: Join orders to order_items; group by customer, product, date; HAVING COUNT(DISTINCT order_id) > 1.

SELECT o.customer_id, oi.product_id, o.order_date
FROM orders o
JOIN order_items oi ON oi.order_id = o.order_id
GROUP BY o.customer_id, oi.product_id, o.order_date
HAVING COUNT(DISTINCT o.order_id) > 1;

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