我正在尝试编写一个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
对于这个问题)
1条答案
按热度按时间p5cysglq1#
使用条件聚合: