0

Hi I'm just learning SQL, I was asked to find the item that was the most popular for each customer. I have these tables:

    create table sales 
    (
        "customer_id" VARCHAR(1),
        "order_date" DATE,
        "product_id" INTEGER
    )
    
  create table  menu 
    (
        "product_id" INTEGER,
    
        "product_name" VARCHAR(5),
        "price" INTEGER
    )

So I did this:

        SELECT sales.customer_id, menu.product_name, COUNT(menu.product_name) AS Times_purchased
    FROM menu
    INNER JOIN sales
    ON menu.product_id = sales.product_id
    GROUP BY sales.customer_id, menu.product_name
    ORDER BY customer_id, Times_purchased DESC

And got this result:

customer_id product_name Times_purchased
A ramen 3
A curry 2
A sushi 1
B sushi 2
B curry 2
B ramen 2
C ramen 3

And Im happy with it since I can point out the popular iteam for each customer. But Is there a way to only see the most populat items and not the rest? I looked at other questions here but I can't make it work

abolfazl sadeghi
  • 2,277
  • 2
  • 12
  • 20
Ale
  • 107
  • 6

1 Answers1

1

First you get most popular for each customer (get Count of Menu)

Then show popular Produnct for each customer(Row_number of Window function)

with _listWithCount as (
        select 
                 customer_id
                ,product_name
                ,COUNT(b.product_name) over(partition by a.customer_id,b.product_id) as Times_purchased
        from sales a
        inner join menu b on a.product_id=b.product_id
)
select customer_id,product_name,Times_purchased
from (
        select *,ROW_NUMBER() over(partition by  customer_id order by Times_purchased desc) rw
        from  _listWithCount
)d
where d.rw=1

Demo

abolfazl sadeghi
  • 2,277
  • 2
  • 12
  • 20
  • sadeghi Hey, yeah its working, thanks! But I dont understand why you made a partition with a.customer_id and b.product_id, specially the product_id from the menu...can you explain it to me ? – – Ale May 23 '23 at 00:29
  • 1
    First, I calculate the count for each customer and product to find out highly of part first (example c:1 p:2 , c:1 p:2 ,c1 p:3 ; result part 1 is c:1 p:2 count:2 ,c:1 p:3 count:1 ;result final is c:1 p:2 count:2 ) if i didn't Calculate count per product and customer,i have count per customer that isn't true – abolfazl sadeghi May 23 '23 at 04:16
  • 1
    I have separated the output of each section so that you may understand more precisely. https://dbfiddle.uk/0DprGLrT If we don't have the count of products per customer, we don't have the most to calculate. Again, if you don't understand, let me explain more – abolfazl sadeghi May 23 '23 at 04:33
  • 1
    sadeghi Yes thank u so much for your time! Im slowly getting it haha thanks again! – Ale May 23 '23 at 14:59