简体   繁体   中英

How to have a query add a ranking by a group of values in DESCENDING order

I have a table of videos

table : 'id', 'video_key, 'week'

values : (1, 12345, 2016-01-03), (2, 23456, 2016-01-03), (3, 3456, 2015-01-03), etc...

The 'week' will always be some Sunday date, and each 'week' can have any number of videos.

I'm trying to come up with a query that orders the videos by 'week' DESC, and has a descending (decremented?) ranking. I'm able to use the following to get videos in incremented ranked order - but this isn't the result I need.

  SELECT tt.*, rank FROM ( SELECT t.*, @week:=
    CASE WHEN @week = week
    THEN  @rank:=@rank +1
    ELSE @rank:=1
    END  rank,
  @week:=t.week
  FROM video_table t ,
    (SELECT @rank:=0,@week:=0) r
  ORDER BY week DESC, id ASC
  ) tt

This returns something like

[id,video_key,week,rank,...]
1,12345,2016-01-03,1,..
2,23456,2016-01-03,2,..
3,3456,2016-01-03,3,....

But I actually need it to be

[id,video_key,week,rank,...]
3,3456,2016-01-03,1,..
2,23456,2016-01-03,2,..
1,12345,2015-01-03,3

My thought is that I need to do a subquery to get the count(*) of videos for each week, and then do something like:

CASE WHEN @week = week
THEN  @weekly_count_of_videos:=@weekly_count_of_videos -1
//....etc

I hope this all makes sense .... thanks for any tips, or pointers to get this going.

UPDATED QUERY based on Gordon Linoff's answer

SELECT t3.* FROM
(SELECT t2.* FROM ( SELECT t1.*, @week:=
    CASE WHEN @week = week
    THEN  @rank:=@rank +1
    ELSE @rank:=1
    END  rank,
  @week:=t1.week
  FROM video_table t1 ,
    (SELECT @rank:=0,@week:=0) r
  ORDER BY week DESC, id ASC
  ) t2)
  t3
  order by week DESC, rank desc

Just make your query a subquery and order by the outer one:

select t.*
from (<your query>
     ) t
order by rank desc;

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