I have three tables items, orders and customers. The items table have product category fields (5 different products) and the orders table have order number sand order dates. If a customer orders five different products then it will have five orders with the same order number. In the customers table I want to add a three fields (product category) to count the number of orders a customer places on that particular category. I just want to do this for only three particular products. I can join all tables with id.
I was thinking about creating three different cte for each product and count if they are in product category 1,2,3 then update the fields accordingly. I tried the below code but it didn't work? Are there any efficient ways to do this? Thanks.
with prod1 as (
select id, count(*) as cnt
from orders
inner join items on orders.id=items.id where i.category=1)
update buyers set category1=prod1.cnt
from prod1
inner join buyers on prod1.indid=buyers.id
↧