统计属于同一客户的产品组合数量。

huangapple go评论75阅读模式
英文:

Count product combinations which are under same customer

问题

我有这样的表格:

Customer_nr Product
11111 Table
22222 Sofa
333333 Table
444444 Closet
11111 Bed

我如何找到由同一客户购买的产品组合的数量?

输出应该如下:

Product A Product B 组合计数
Table Bed 245

这意味着有 245 位客户购买了桌子和床。

英文:

I have table like this:

Customer_nr Product
11111 Table
22222 Sofa
333333 Table
444444 Closet
11111 Bed

How can I find the number of product combination that a bought by same customer?

Out come should be like that:

Product A Product B Count of combination
Table Bed 245

It mean that 245 customers bought table and bed

答案1

得分: 2

执行自连接并按如下方式聚合:

select t.Product Product_A, d.Product Product_B,
  count(*) com_cnt
from table_name t join table_name d
on d.Customer_nr = t.Customer_nr and
   d.Product > t.Product
group by t.Product, d.Product

demo

英文:

Do a self-join and aggregate as the following:

select t.Product Product_A, d.Product Product_B,
  count(*) com_cnt
from table_name t join table_name d
on d.Customer_nr = t.Customer_nr and
   d.Product > t.Product
group by t.Product, d.Product

demo

答案2

得分: 0

如果您想统计特定组合,请使用 group byhaving

首先,识别购买了这些产品的客户:

select customer_nr
from mytable
where product in ('Table', 'Bed')
group by customer_nr
having count(distinct product) = 2

然后统计有多少客户:

select 'Table' as 'product A', 'Bed' as 'product B', count(distinct customer_nr) 
from (
  select customer_nr
  from mytable
  where product in ('Table', 'Bed')
  group by customer_nr
  having count(distinct product) = 2
) as s

在此查看演示

英文:

If you want to count a specific combination, then use group by and having :

First, identify the customers who purchased those products:

select customer_nr
from mytable
where product in ('Table', 'Bed')
group by customer_nr
having count(distinct product) = 2

Then count how many customers there are:

select 'Table' as 'product A', 'Bed' as 'product B', count(distinct customer_nr) 
from (
  select customer_nr
  from mytable
  where product in ('Table', 'Bed')
  group by customer_nr
  having count(distinct product) = 2
) as s

Demo here on mysql

huangapple
  • 本文由 发表于 2023年5月26日 15:32:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76338584.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定