I’m working on MySQL workbench 8.0 and I would like to find the number of types of buyers for each product per user_id. For instance, for chairs, if user_id 1, user_id 2, and user_id 3 make purchases only once, I would like to create a column (type of buyer), "BoughtOnce" and add the number of chairs that were purchased; 3 chairs (bought once by each user).
The sample data similar to the original one is shown below.
user_id | Product |
---|---|
1 | chair |
1 | bed |
2 | bed |
1 | chair |
3 | bed |
2 | sofa |
3 | sofa |
3 | shelf |
2 | chair |
And I would like to find the following result:
Product | BoughtOnce | BoughtTwice |
---|---|---|
chair | 1 | 2 |
bed | 3 | Null |
sofa | 2 | Null |
shelf | 1 | Null |
For instance, user_id 1 bought 2 chairs and user_id 2 bought 1 chair.
I wanted to use the expression below but realized I could not aggregate a window function.
CASE WHEN COUNT(DISTINCT Prodcut) OVER (PARTITION BY user_id) = 1 Then …
Could anyone help me with this? I’d appreciate your help!
It’d be helpful if you suggest another approach as well.
2
Answers
With a CTE that gets the number of times one userid gets an item, you then count the occurances of the row_number for a product
fiddle
Twice grouping
Result
Example