MariaDb 每月每日結算排名Ranking
目前有一張table 來記錄每天的各個user的netprofit
daily profit table結構 這個表回去結算每天的daily profit
id username netprofit date
1 testuser01 20 2020/09/27 14:00:00
2 testuser02 30 2020/09/27 14:00:00
3 testuser03 40 2020/09/27 14:00:00
4 testuser02 20 2020/09/26 14:00:00
5 testuser03 30 2020/09/26 14:00:00
6 testuser03 30 2020/08/27 14:00:00
7 testuser01 20 2020/08/27 14:00:00
8 testuser03 30 2019/12/01 14:00:00
9 testuser01 20 2019/12/01 14:00:00
主管要求做出以下的部分,
按照每天profit來進行ranking排名
username netprofit date rank
testuser03 40 2020/09/27 14:00:00 1
testuser02 30 2020/09/27 14:00:00 2
testuser01 20 2020/09/27 14:00:00 3
testuser03 30 2020/09/26 14:00:00 1
testuser02 20 2020/09/26 14:00:00 2
testuser03 30 2020/08/27 14:00:00 1
testuser01 20 2020/08/27 14:00:00 2
按照每月profit來進行ranking排名
username netprofit date rank
testuser03 70 2020/09 1
testuser02 50 2020/09 2
testuser01 20 2020/09 3
testuser03 30 2020/08 1
testuser01 20 2020/08 2
testuser03 30 2019/12 1
testuser01 20 2019/12 2
請問有辦法做出這樣的View嗎?
還是有其它建議的做法, 比如開多2個table來分別進行結算?
謝謝
CREATE TABLE daily
(id nvarchar(30),
username nvarchar(30),
netprofit nvarchar(30),
date datetime
);
insert into daily
values
('1','testuser01','20','2020/09/27 14:00:00'),
('2','testuser02','30','2020/09/27 14:00:00'),
('3','testuser03','40','2020/09/27 14:00:00'),
('4','testuser02','20','2020/09/26 14:00:00'),
('5','testuser03','30','2020/09/26 14:00:00'),
('6','testuser03','30','2020/08/27 14:00:00'),
('7','testuser01','20','2020/08/27 14:00:00'),
('8','testuser03','30','2019/12/01 14:00:00'),
('9','testuser01','20','2019/12/01 14:00:00');
select *
from daily;
-- 每天 : row_number()
select username,netprofit,date,
row_number()
over(partition by date order by date desc,netprofit desc,username) as rank
from daily
order by date desc,netprofit desc
-- 每月 : row_number()
select username,netprofit,date_format(date,'%Y-%m') as date,
row_number()
over(partition by date_format(date,'%Y-%m') order by date_format(date, '%Y-%m') desc,netprofit desc) as rank
from daily
order by date_format(date,'%Y-%m') desc,netprofit desc
使用 row_number(),rank(),dense_rank() 時機依照需求自行變更
SELECT
`username`,
`netprofit`,
DATE_FORMAT(`date`,'%Y/%m'),
RANK() OVER(
PARTITION BY YEAR(`date`),
MONTH(`date`)
ORDER BY
`netprofit`
DESC
) rank
FROM
`rank` #日結完可以直接放在這邊轉月