简体   繁体   中英

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.

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

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.

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 dbfiddle

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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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