旋转并获得排名

Pivot and also get ranking

我正在尝试编写一个 SQL,它可以 pivot 并且还可以在一行中获得其 ranking 顺序。不知道如何。

示例:

旋转 area 但也获得 cost 的排名(最贵的顺序)

table name: aaa

entity_id | entity_type | datetime   | area | cost
----------+-------------+------+-----+------+-----
123       | ITEM        | 2020-01-01 | US   | 8
123       | ITEM        | 2020-01-01 | AP   | 7
123       | ITEM        | 2020-01-01 | EU   | 6
123       | ITEM        | 2020-01-02 | US   | 1
123       | ITEM        | 2020-01-02 | AP   | 2
123       | ITEM        | 2020-01-02 | EU   | 3
888       | BOX         | 2020-01-01 | US   | 8
888       | BOX         | 2020-01-01 | AP   | 7
888       | BOX         | 2020-01-01 | EU   | 6
888       | BOX         | 2020-01-02 | US   | 1
888       | BOX         | 2020-01-02 | AP   | 2
888       | BOX         | 2020-01-02 | EU   | 3

我想要的是:

entity_id | entity_type | datetime   | US | AP | EU | US_rank | AP_rank | EU_rank
----------+-------------+------------+----+----+----+---------+---------+---------
123       | ITEM        | 2020-01-01 | 8  | 7  | 6  | 1       | 2       | 3
123       | ITEM        | 2020-01-02 | 8  | 7  | 6  | 3       | 2       | 1
888       | BOX         | 2020-01-01 | 8  | 7  | 6  | 1       | 2       | 3
888       | BOX         | 2020-01-02 | 8  | 7  | 6  | 3       | 2       | 1

目前,我只会旋转。不确定如何获得 'ranking' 部分

SELECT  
  p.entity_id, p.entity_type, p.[datetime], p.[US], p.[AP], p.[EU]
FROM
  aaa as a
PIVOT
(
  MAX(cost)
  FOR area IN ([US], [AP], [EU])
) p

(which returns)

entity_id | entity_type | datetime   | US | AP | EU 
----------+-------------+------------+----+----+----
123       | ITEM        | 2020-01-01 | 8  | 7  | 6  
123       | ITEM        | 2020-01-02 | 8  | 7  | 6  
888       | BOX         | 2020-01-01 | 8  | 7  | 6  
888       | BOX         | 2020-01-02 | 8  | 7  | 6  

我假设我需要在旋转之前将其添加到某处,但不确定之后要做什么

ranking = ROW_NUMBER() OVER(PARTITION BY entity_id, entity_type, [datetime] ORDER BY cost DESC)

(我不介意使用 RANKROW_NUMBER 来解决这个问题)

使用条件聚合:

select entity_id, entity_type, datetime,
       max(case when area = 'US' then cost end) as us,
       max(case when area = 'AP' then cost end) as ap,
       max(case when area = 'EU' then cost end) as eu,
       max(case when area = 'US' then rnk end) as us_rank,
       max(case when area = 'AP' then rnk end) as ap_rank,
       max(case when area = 'EU' then rnk end) as eu_rank
from (select s.*,
             rank() over (partition by entity_id, entity_type, datetime 
                          order by cost desc
                         ) as rnk
      from aaa a
     ) a
group by entity_id, entity_type, datetime