订购了最多常见产品的夫妇 - SQL

时间:2017-10-13 13:33:30

标签: mysql sql

我无法选择订购了最多常见产品的客户。

示例:

  • 客户1订购产品:a,b,c,z
  • 客户2订购产品:a,c,d,g
  • 客户1订购产品:g,h,z

预期结果:Customer1 |客户2 | 2(订购的常见产品数量)

我尝试了什么:

SELECT c.pid, c.cid, d.cid, count(c.pid)
FROM orders c JOIN orders d join 
(SELECT a.cid, b.cid FROM customers a JOIN customers b ON b.cname != a.cname AND b.cname > a.cname) as subq
ON c.cid = a.cid and d.cid = b.cid
AND c.pid = d.pid group by c.pid;

这将返回每个名称:

select a.cname client_1, b.cname client_2
from customers a join customers b on b.cname != a.cname and b.cname > a.cname;

如何获得几个cid的常用pid的最大值?

表格:

customers (cid, cname, residence)
orders (pid, cid, odate, quantity)
products (pid, pname, price, origin)

1 个答案:

答案 0 :(得分:0)

可能无法在每个RDBMS中工作。你在用哪一个?

select o1.cid, o2.cid, o1.pid, o1.cnt, o2.cnt
from (
 select cid, pid, count(*) as cnt
 , ROW_NUMBER() OVER(PARTITION BY cid, pid ORDER BY count(*) DESC) AS rn
 from order
 group by cid, pid
) as o1
join (
 select cid, pid, count(*) as cnt
 , ROW_NUMBER() OVER(PARTITION BY cid, pid ORDER BY count(*) DESC) AS rn
 from order
 group by cid, pid
) as o2
on o1.cid <> o2.cid
and o1.pid = o2.pid

where o1.rn = 1
 and o2.rn = 1