2013-10-06 18 views
0

我有一個表是這樣的:SQL行值排名爲序

╔═══════════════════════╗ 
║ id name  spent ║ 
╠═══════════════════════╣ 
║ 1 John  1000 ║ 
║ 2 Bob  2000 ║ 
║ 3 Richard 5000 ║ 
║ 4 Jane  2000 ║ 
║ 5 Anthony 2500 ║ 
╚═══════════════════════╝ 

我想檢索行和排名是這樣

SELECT name, 
     spent 
FROM table 
WHERE id = 5 ; 

用過柱和期望的結果是是這樣的:

╔══════════════════════╗ 
║ name  spent ║ 
╠══════════════════════╣ 
║ Anthony 2500 (2nd) ║ 
╚══════════════════════╝ 

也就是說,安東尼是誰花大部分的第二(理查德的5000之後)如果我想用誰花了更少的訂貨會是這樣的

╔══════════════════════╗ 
║ name  spent ║ 
╠══════════════════════╣ 
║ Anthony 2500 (4th) ║ 
╚══════════════════════╝ 
+0

我沒有看到企圖... –

+1

如果您在SO搜索「MySQL的排名」,我敢打賭,你會發現很多的答案 - 這是一種常見的需要。 – Barmar

+0

我剛剛發現了一個有趣的方法來計算有多少行花費了大於或小於當前行值的行數,如'select count(1)from users where spent>(select from users where id = 5)' – ethmz

回答

0

這裏是解決方案:

排序誰花更少

SELECT id, name, group_concat(spent,' (', rank,')') as t from (
    SELECT id, name, spent, FIND_IN_SET(spent, (
    SELECT GROUP_CONCAT(spent 
         ORDER BY spent) 
FROM t1) 
) AS rank 
FROM t1) as y 
where id = 5 
group by id, name 
order by spent; 

SQL Fiddle

排序方式誰花更多

SELECT id, name, group_concat(spent,' (', rank,')') as t from (
    SELECT id, name, spent, FIND_IN_SET(spent, (
    SELECT GROUP_CONCAT(spent 
         ORDER BY spent DESC) 
FROM t1) 
) AS rank 
FROM t1) as y 
where id = 5 
group by id, name 
order by spent; 

SQL Fiddle