Mysql创建一个名为Rank的行

时间:2017-07-10 15:43:07

标签: php mysql

让我从我的问题中告诉你一个例子 例如,我们有一个名为(order)的表,它将所有订单和购买插入此表。

表A(订单):

+--------------------------+
| CustomerKey | ProductKey |
+--------------------------+
| 306545      | pro1       |
| 597864      | pro3       |
| 784678      | pro2       |
| 905479      | pro3       |
| 306545      | pro1       |
| 348965      | pro3       |
| 784678      | 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

但它不完整!这个查询需要一行名为rank(查看下面的查询输出):

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

2 个答案:

答案 0 :(得分:0)

这可能就是你要找的东西:

SET @rank=0;
SELECT 
    ProductKey, 
    count(1) AS numberSold, 
    @rank:=@rank+1 AS rank 
  FROM A 
  GROUP BY ProductKey ORDER BY numberSold DESC

答案 1 :(得分:0)

或...如果您更喜欢单一查询方法......

SELECT a.*
     , @rank:=@rank+1 rank 
  FROM 
     ( SELECT ProductKey
            , COUNT(1) numberSold
         FROM my_table
        GROUP 
           BY ProductKey 
     ) a
     , (SELECT @rank:=0) vars
 ORDER 
    BY numberSold DESC;