2017-07-10 82 views
1

讓我告訴你一個來自我的問題的例子。
例如,我們有一個名爲(訂單)的表格,它將插入所有訂單併購買到此表格。Mysql創建一個名爲Rank的行

表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 

但它不完整!此查詢需要的行命名爲秩(請看下面的查詢輸出):

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

你想要一個_column_,而不是_row_。 – arkascha

+0

您需要嘗試**自己編寫代碼**。在[**做更多的研究**之後](https://meta.stackoverflow.com/q/261592/1011527)如果你有問題**發佈你已經嘗試過**的**清楚的解釋不工作**並提供[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。閱讀[如何問](http://stackoverflow.com/help/how-to-ask)一個很好的問題。請務必[參觀](http://stackoverflow.com/tour)並閱讀[this](https://meta.stackoverflow.com/q/347937/1011527)。 –

回答

0

也許這是你在找什麼:

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

或...如果你喜歡單查詢方法...

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