简体   繁体   English

查找 SQL 中的所有组合,包括重复项

[英]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.如果我对列表进行排序,“Apple, Banana”的组合仍然不会接近组合中首先提到 Banana 的列表。

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.如果组合包含 3 个或更多产品,则在第一个产品之后订购无关紧要。

You can use string_agg() and two levels of aggregation:您可以使用string_agg()和两个级别的聚合:

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. 是一个 db<>fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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