2014-01-15 96 views
0

所以,我的問題是,我有一個客戶名單(現在有大約10萬條記錄),每個客戶都有收入。當我按國家進行分組時,我可以獲得大約60個國家的收入總和。比我更需要通過收入DESC來訂購吧,我的查詢看起來是這樣的:通過mysql訂購後創建一個唯一的列值

SELECT s2.i,s1.year,s1.short_c,s1.country,s1.uges FROM 
(SELECT u.year,k.short_c,s.country, IFNULL(ROUND(SUM(u.income)),0) as uges 
    FROM im_income u,im_contact k,td_countries s 
    WHERE u.year=2012 
    AND u.customer_id=k.id 
    AND k.kat='K' 
    AND k.short_c=s.short_c 
    GROUP BY k.short_c, u.year 
    ORDER BY u.year ASC,uges DESC) s1 
CROSS JOIN 
(SELECT @i:[email protected]+1 as i FROM (SELECT @i:= 0) AS i) s2 

而且我知道,這與CROSS JOIN是錯誤的,因爲它不給我我需要什麼,但有什麼辦法在ORDER BY之後創建一個唯一的ID,因爲我需要訂購具有收入DESC的國家,並且比給他們分配代表排名數字的ID?

結果看起來像現在這樣:

+-+----+-------+---------+------+ 
|i|year|short_c|country |uges | 
+-+----+-------+---------+------+ 
|1|2012|USA |United S.|123456| 
+-+----+-------+---------+------+ 
|1|2012|RU  |Russia |23456 | 
+-+----+-------+---------+------+ 

而且我希望它以這種方式,而是通過獨有的I值的訂單後分配:

+-+----+-------+---------+------+ 
|i|year|short_c|country |uges | 
+-+----+-------+---------+------+ 
|1|2012|USA |United S.|123456| 
+-+----+-------+---------+------+ 
|2|2012|RU  |Russia |23456 | 
+-+----+-------+---------+------+ 
|3| |  |   |  | 
+-+----+-------+---------+------+ 

任何幫助,將不勝感激。

回答

1

我認爲這是你在找什麼:

SELECT @i := @i + 1 as i, s1.year, s1.short_c, s1.country, s1.uges 
FROM (SELECT u.year, 
      k.short_c, 
      s.country, 
      IFNULL(ROUND(SUM(u.income)),0) as uges 
     FROM im_income u join 
      im_contact k 
      on u.customer_id = k.id join 
      td_countries s 
      on k.short_c = s.short_c 
     WHERE u.year = 2012 AND k.kat = 'K' 
     GROUP BY k.short_c, u.year 
    ) s1 
    CROSS JOIN 
    (SELECT @i:= 0) const 
ORDER BY year, uges desc; 

當結果是「輸出」,由訂單後,會出現變量賦值。

我還修復了您的join語法。您應該學會在where子句中使用顯式join而不是隱式聯接。