【问题标题】:Count distinct occurrences in all combinations of a column?计算列的所有组合中的不同出现次数?
【发布时间】:2021-04-01 03:54:36
【问题描述】:

我有一个包含某些类别出现次数的表格:

USER ID CATEGORY
A Mobile
A Website
A e-commerce
B Mobile
B Website
C e-commerce

我想生成所有可能的组合并计算符合此组合的用户 ID 的唯一出现次数,例如:

Categories Counts
Mobile 3
e-commerce 2
Mobile, Website 2
Mobile, Onsite 0
Mobile, e-commerce 1
Mobile, Website, Onsite 0
Mobile, Website, Onsite, e-commerce 0

...等

有可能吗?

【问题讨论】:

  • Edit 问题并展示您已经尝试过的内容。解释失败的原因/位置。具体(错误消息、意外结果等)。
  • 用您正在使用的数据库标记您的问题。

标签: sql


【解决方案1】:

根据 cmets;不确定您使用的是什么 RMDBS,但基本上这就是您想要的

SELECT Category, COUNT(UserId) AS Counts
FROM TABLE
GROUP BY Categroy

【讨论】:

    【解决方案2】:

    可以显式查询每组组合:

    select category, count(*)
    from t
    group by category
    union all
    select t1.category || ',' || t2.category, count(*)
    from t t1 join
         t t2
         on t1.userid = t2.userid and t1.category < t2.category
    group by t1.category || ',' || t2.category
    union all
    select t1.category || ',' || t2.category ',' || t3.category, count(*)
    from t t1 join
         t t2
         on t1.userid = t2.userid and t1.category < t2.category join
         t t3
         on t2.userid = t3.userid and t2.category < t3.category
    group by t1.category || ',' || t2.category ',' || t3.category;
    

    以上内容可以满足您最多 3 种组合的需求。您可以为更大的组合添加更多类似的子查询。

    【讨论】:

      猜你喜欢
      • 2014-04-09
      • 2011-05-06
      • 1970-01-01
      • 2018-10-03
      • 2011-02-21
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多