訂便當一段時間之後,總是需要排名.假設雞腿跟便當各有前10的,做排名,
還有到另一組時會排名第幾?
為了方便大家研究,不用亂數,使用循序的產生.
create table 雞腿組 (
  id int not null primary key
, val int
);
create table 排骨組 (
  id int not null primary key
, val int
);
insert into 雞腿組
select n, 6 + 10 * n
  from generate_series(1, 10) n;
insert into 排骨組
select n, 4 + 10 * n
  from generate_series(1, 10) n;
select id, val
     , rank() over(order by val desc)
  from 雞腿組;
 id | val | rank 
----+-----+------
 10 | 106 |    1
  9 |  96 |    2
  8 |  86 |    3
  7 |  76 |    4
  6 |  66 |    5
  5 |  56 |    6
  4 |  46 |    7
  3 |  36 |    8
  2 |  26 |    9
  1 |  16 |   10
(10 rows)
方便測試用,已經做好線上的 按我前往
想要做到如下圖:
記得 RANK(Value) WITHIN GROUP (...) 可以把某個值放到特定群中取得排名
這樣就可以解出
select val as 排骨組val, 
  (select RANK(排骨組.val) WITHIN GROUP (order by 雞腿組.val desc) from 雞腿組) as 在雞腿組排名
  from 排骨組
  order by 2;
