简体   繁体   中英

Find all the combinations in SQL including duplicates

Lets assume I have a table of orders

ID,  Products
----  ----
1     Banana
1     Apple
1     Pear
2     Apple
2     Banana
3     Banana
3     Apple
4     Banana
4     Pear

I need to count how many times the same products were bought. I have tried some different methods(inner joins; create a ranking and pivot the data) however the issue I have that it counts once(my results table):

Combination,           Total
------                 -----
Banana, Apple, Pear      1
Apple, Banana            2
Banana, Pear             1

This should be enough when we have a small list of orders, however when the list contains thousands of rows it becomes quite hard to look into these results. Assume I only care to see combinations which contains Banana. If I order the list, the combination of 'Apple, Banana' will still be somewhere not near to the list where Banana was mentioned first in the combination.

So I need to see results for each product to be first in combination list(I don't care about duplicates). So the result table should look like this:

Combination,           Total
------                 -----
Apple, Banana, Pear      1
Apple, Banana            2
Banana, Apple, Pear      1
Banana, Apple            2
Banana, Pear             1
Pear, Apple, Banana      1
Pear, Banana             1

Notes: Combinations can be split in different columns or separated by symbol. If the combination consist of 3 or more products, ordering after the first product doesn't matter.

You can use string_agg() and two levels of aggregation:

select products, count(*) as num_orders
from (select id,
             string_agg(product, ', ') within group (order by product) as products
      from orders o
      group by id
     ) o
group by products;

Here is a db<>fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM