Counting unique combinations

我与影子孤独终老i 提交于 2021-01-29 18:41:58

问题


I have a table in the following format:

And I am trying to find a way to count different combinations of the categories. Here is the output I am looking for:

I tried grouping the Category field, but I cannot figure out a way to create a unique combination. Screenshots are in excel, simply for illustration purposes. Actual data is in ms-access.


回答1:


First get the unique pairs in a subquery and then join twice to the table to group and count:

select 
  t1.Category & '+' & t2.Category as Category, count(*) as Count
from (
  select t1.category as cat1, t2.category as cat2
  from tablename as t1, tablename as t2
  where not (t1.id = t2.id and t1.category = t2.category) and (t1.category < t2.category)
  group by t1.category, t2.category
) as t, tablename as t1, tablename as t2 
where t1.category = t.cat1 and t2.category =  t.cat2 and t1.id = t2.id
group by t1.Category & '+' & t2.Category


来源:https://stackoverflow.com/questions/57316456/counting-unique-combinations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!