2017-10-13 61 views
0

我無法選擇已訂購最多常見產品的幾位客戶。已訂購最多常見產品的夫婦 - SQL

實施例:

  • customer1表訂購的產品:A,B,C,Z
  • 顧客2訂購產品:A,C,d,克
  • customer1表訂購的產品:G,H,Z

預期結果:Customer1 | Customer2 | 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; 

我怎樣才能得到共同的PID的最大的一對夫婦的cids?

表:

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

請使用帶格式的文本而不是圖片。 (或者,更糟的是,鏈接到圖像。) – jarlh

+0

對不起,我改變了它 – Lou

回答

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 
+0

嗨,謝謝你的回答。我使用的是Mysql,它說在over子句中有一個缺少的括號,但是我沒有看到任何缺失...... – Lou

+0

是的,我認爲MySQL只支持啓動下一個版本的窗口功能。你必須過濾每個子查詢,比如'where exists(從cid,pid中選擇cid,max(cnt)m_cnt from(選擇cid,pid,count(*)作爲cnt來自order group)a)group by cid max(cnt)= outer_query.cnt)' – Alex