These are the tables I have:
sales
(
"customer_id" VARCHAR(1),
"order_date" DATE,
"product_id" INTEGER
);
menu
(
"product_id" INTEGER,
"product_name" VARCHAR(5),
"price" INTEGER
);
I'm trying to find what was the first item from the menu purchased by each customer. So after a couple of hours I got to this solution:
WITH cte_product AS
(
SELECT
sales.customer_id, menu.product_name,
ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY customer_id) row_a
FROM
sales
INNER JOIN
menu ON sales.product_id = menu.product_id
)
SELECT *
FROM cte_product
WHERE row_a = 1
And this in fact gives me back only the first order each customer made by date.
Although I'm happy to have an answer, I'm wondering if there is another way to do this. A more simple way perhaps?
I previously tried DISTINCT
, ORDER BY
, WHERE
and GROUP BY
without success, but I'm new in this, so I'm here to ask you guys if this is a good enough way or if there is a better way to do it.