1. 程式人生 > >mysql 按周進行分組 & Rank

mysql 按周進行分組 & Rank

select
ADDDATE(‘1970-01-05’, INTERVAL FLOOR(DATEDIFF(nowtime, ‘1970-01-05’) / 7) * 7 DAY) as start,
ADDDATE(‘1970-01-05’, INTERVAL FLOOR(DATEDIFF(nowtime, ‘1970-01-05’) / 7) * 7 + 6 DAY) as end
GROUP BY start, end;

RANK 問題:
SET @prev_value = NULL;
SET @rank_count = 0;

SELECT id, score,
CASE
WHEN @prev_value = score then @rank_count
WHEN @prev_value := score then @rank_count := @rank_count + 1
END as rank_n
FROM rank ORDER BY score DESC ;

One Query:

SELECT id, score,
CASE
WHEN @prev_value = score then @rank_count
WHEN @prev_value := score then @rank_count := @rank_count + 1
END as rank_n
FROM rank, (select @prev_value:=NULL) as pre, (select @rank_count:=0) as rank_ ORDER BY score DESC ;