pivot并获得排名

of1yzvn4  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(424)

我正在尝试编写一个sql,它可以在一行中透视并获得它的排名顺序。不知道怎么做。
例子:
枢轴 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

目前,我只知道如何旋转。不知道如何获得“排名”部分

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)

(我不介意使用 RANK 或者 ROW_NUMBER 对于这个问题)

p5cysglq

p5cysglq1#

使用条件聚合:

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

相关问题