我正在尝试编写一个可以透视并在一行中获取其排名顺序的 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
来解决这个问题(
使用条件聚合:
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