MySQL之如何巧用變數

來源:互聯網
上載者:User

標籤:觀察   core   3.0   --   tab   scores   generate   工作   value   

Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.

+----+-------+| Id | Score |+----+-------+| 1  | 3.50  || 2  | 3.65  || 3  | 4.00  || 4  | 3.85  || 5  | 4.00  || 6  | 3.65  |+----+-------+

For example, given the above Scores table, your query should generate the following report (order by highest score):

+-------+------+| Score | Rank |+-------+------+| 4.00  | 1    || 4.00  | 1    || 3.85  | 2    || 3.65  | 3    || 3.65  | 3    || 3.50  | 4    |+-------+------+

該問題讓我們對Score添加權重,相同的值有相同的權重,且權重是連續的數字。

如果是編程的話肯定很容易解決,不過放到SQL語句裡就不見得很容易解決了。從思路來說,這個解法很簡單,只要先對score排序,如果當前score的值比前一個score的值大,權重就自增1。如果不大於前一個score就保持原值

如果把後邊的條件化簡,我們的工作其實就是給score排序後加上序號。這時我們的操作就變得簡單了。
select (@i:=@i+1) as i,table_name.* from table_name,(select @i:=0) as it

上述是從網上隨便找到一個自動添加序號的語句。我們觀察上面的SQL語句,並分析含有變數的SQL語句的結構。

首先把幹擾項as去掉,as只是給查詢結果取了一個別名,此處我們不必考慮as。

select score , (@i:=@i+1)from Scores,(select @i:=0) init order by score desc

這樣的輸出結果是:

{"headers": ["score", "(@i:[email protected]+1)"], "values": [[4.00, 1.0], [4.00, 2.0], [3.85, 3.0], [3.65, 4.0], [3.65, 5.0], [3.50, 6.0]]}

看看上面的結果,我們已經實現了一半的要求了。只不過現在結果中的序號沒有滿足“相同的值有相同的權重”這個要求。此時我們需要引入另一個變數@pre來儲存上一個score。

當計算權重時如果@pre跟當前score相等,則@i保持原值(或者說+0),否則加1.

select     Score,     @i := @i + (@pre <> ( @pre := Score)) Rank from     Scores,     (select @i := 0,@pre := -1) init order by Score desc

這裡需要注意的是變數@pre。由於我們在權重那裡判斷是根據@pre(前一個score的值)是否等於當前score的值,如果@pre的初始值為大於0的數,就可能判斷出錯。最好@pre的初始值設定為小於0的數。

MySQL之如何巧用變數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.