2017-08-14 64 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';