0

我有一张这样的桌子:

╔═══════════════════════╗
║ 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) ║
╚══════════════════════╝
4

1 回答 1

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小提琴

订购者花费更多

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小提琴

于 2013-10-06T04:39:14.170 回答