所以,我的问题是我有一个客户列表(表现在有大约10万条记录),每个客户都有收入。当我按国家分组时,我会收到大约60个国家的收入。我需要通过收入DESC来订购它,我的查询看起来像这样:
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:=@i+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| | | | |
+-+----+-------+---------+------+
任何帮助都将不胜感激。
答案 0 :(得分: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
语法。您应该学会在join
子句中使用显式where
而不是隐式连接。