简体   繁体   English

如何使查询按DESCENDING顺序按一组值添加排名

[英]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' 表格 :“ id”,“ video_key,“ week”

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

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. 我正在尝试提出一个查询,该查询按“周” DESC排序视频,并具有降序降级 ?)的排名。 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;

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

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