Skip to the content

You started with a Keyboard

Problem

The store wants to write each customer something that's about them: "You started with a Keyboard. The last thing you ordered was a Mouse."

For each customer who has ordered something, show three columns, in this order: their name, the product from their first order, and the product from their last. Sort alphabetically by customer. Someone who has ordered only once gets the same product in both columns.

Which order came first is decided by date and, within the same day, by order number. The one dated the 20th has a mistyped date, but whether it's the 15th or the 20th, it's the last thing Luke ordered, and it counts.

What it has to return

These rows, in this order

customerearliestlatest
AnnKeyboardMouse
ChloëHeadphonesHeadphones
DylanLaptopHeadphones
LukeMouseTablet
MasonCableCable
ValerieKeyboardCable

This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.

You start with this

SQL

SELECT o.customer_id,
  p.name AS product,
  ROW_NUMBER() OVER (
    PARTITION BY o.customer_id
    ORDER BY o.placed, o.id
  ) AS num
FROM orders o
JOIN products p
  ON o.product_id = p.id;
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n²) challenges

See all challenges →