简体   繁体   English

对多列和条件的记录进行排序

[英]Sort records on multiple columns and conditions

I have the below table, that stores the rank of person participating in respective events.我有下表,其中存储了参加相应活动的人员的排名。

event_running and event_jumping are the events and the ranks stored. event_running 和 event_jumping 是存储的事件和排名。

CREATE TABLE `ranks` (
  `id` int(11) NOT NULL,
  `personid` int(11) NOT NULL,
  `event_running` int(11) DEFAULT NULL,
  `event_longjump` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Sample data样本数据

INSERT INTO `ranks` (`id`, `personid`, `event_running`, `event_longjump`) VALUES
(1, 1, 4, 8),
(2, 2, 10, 6),
(3, 3, 5, 0),
(4, 5, 20, 1),
(5, 4, 9, 3),
(6, 6, 1, 2);

SQL Fiddle Link SQL 小提琴链接

I want to build a leaderboard as below我想建立一个如下的排行榜

| Standing | PersonID | RunningRank | JumpingRank |
|     1    |     6    |      1      |       2     |
|     2    |     4    |      9      |       3     |
|     3    |     1    |      4      |       8     |
|     4    |     3    |      5      |       0     |
|     5    |     2    |      10     |       6     |

This has to be sorted in ascending order - irrespective of the events lowest come first and also ranks above 20 are ignored.这必须按升序排序 - 无论最低的事件如何,排名在 20 以上的都将被忽略。

And inputs on how can this be done?以及如何做到这一点的意见?

you can use something similar to below你可以使用类似于下面的东西

select PersonID,
       RunningRank,
       JumpingRank,
       (RunningRank + JumpingRank) as Total
from ranks
order by Total asc
limit 20;

Here's your query.这是您的查询。

set @row_number = 0; 

select  (@row_number:=@row_number + 1) as standing, personid, event_running, event_longjump from ranks
where event_running < 20 and event_longjump < 20
order by 
    case when if(event_longjump=0,event_running ,event_longjump) < event_running
         then event_longjump else event_running end  

see dbfiddledbfiddle

Your sorting criteria is a bit vague.你的排序标准有点模糊。 I am assuming that you want to sort on the basis of cumulative of the ranks across all events and its jumping score.我假设您想根据所有事件的排名累积及其跳跃分数进行排序。

Also, please explain the position of person Id 3 in your queation .另外,请解释第 3 个人在您的问题中的位置 You can do,你可以做,

select PersonID,
       RunningRank,
       JumpingRank,
       (JumpingRank + RunningRank) as cumulativeRank
from ranks
ORDER BY cumulativeRank, JumpingRank aesc
limit 20;

This will get you all the positions baring person id 3这将使您获得所有职位,不包含人员 ID 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM