2017-08-14 62 views
0

讓我告訴你一個我遇到的問題的例子。例如,我們有名爲order的表格,我們插入所有訂單和購買。獲得bestsell產品的產品排名MySQL

表A(orders):

+--------------------------+ 
| CustomerKey | ProductKey | 
+--------------------------+ 
| 306545  | pro1  | 
| 597864  | pro3  | 
| 784678  | pro2  | 
| 905479  | pro3  | 
| 306545  | pro1  | 
| 348965  | pro3  | 
| 784678  | pro3  | 
+--------------------------+ 

現在我想訂購,並得到我們最暢銷的產品,例如獲得PRO3排名中最暢銷的產品清單。

查詢輸出:

+-------------------------------+ 
| id | ProductKey | numberSold | 
+-------------------------------+ 
| 1 | pro3  | 4   | 
| 2 | pro1  | 2   | 
| 3 | pro2  | 1   | 
+-------------------------------+  

我寫此查詢:

select ProductKey, 
count(1) as numberSold 
from A group 
by ProductKey 
order by count(1) desc 

結果是不是對我很有用。例如,我需要將pro27排在暢銷產品(我們有100,000個產品!)

+-------------------------------------+ 
| id | ProductKey | numberSold | rank | 
+-------------------------------------| 
| 1 | pro3  | 4   | 1 | 
| 2 | pro1  | 2   | 2 | 
| 3 | pro2  | 1   | 3 | 
+------------------------------+------+ 
+0

等待,爲什麼不只是'SELECT ProductKey FROM A ORDER BY numberSold DESC LIMIT 1'?您在查詢中獲得最高賣家。 – GrumpyCrouton

+0

請參閱:[爲什麼我應該爲我認爲是非常簡單的SQL查詢提供一個MCVE?](https://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve -for - 什麼 - 似乎對我將要-A-極簡單的SQL查詢) – Strawberry

回答

1

您可以使用派生表來解決此問題。查詢速度很慢,但它會給你你想要的結果。

SET @rank = 0; 

SELECT * 
FROM 
(
    select (@rank := @rank + 1) AS Rank, 
    ProductKey, 
    count(1) as numberSold 
    from A 
    group by ProductKey 
    order by count(1) desc 
) dt 
WHERE dt.ProductKey = 'prod27';