SQL-如何在列中获取唯一值(此处不起作用)

时间:2018-08-16 12:56:23

标签: sql distinct rank presto

我有一个生产案例,我们跟踪在仓库中移动的设备。我有一张表,显示这些以前的位置,例如:

+--------+------------+-----------+------+
| device | current_WH |   date    | rank |
+--------+------------+-----------+------+
|      1 | AB         | 3/15/2018 |    7 |
|      1 | CC         | 3/19/2018 |    6 |
|      1 | CC         | 3/22/2018 |    5 |
|      1 | CC         | 3/22/2018 |    5 |
|      1 | DD         | 4/23/2018 |    4 |
|      1 | DD         | 5/11/2018 |    3 |
|      1 | DD         | 5/15/2018 |    2 |
|      1 | DD         | 5/15/2018 |    2 |
|      1 | AA         | 6/6/2018  |    1 |
|      1 | AA         | 6/6/2018  |    1 |
+--------+------------+-----------+------+

但是我需要找到current_WH的那些唯一值,并将设备减少到一行(有数百万个设备),像这样:

+--------+------------+--------+--------+--------+
| device | current_WH | prev_1 | prev_2 | prev_3 |
+--------+------------+--------+--------+--------+
|      1 | AA         | DD     | CC     | AB     |
+--------+------------+--------+--------+--------+

我使用了排名功能(按日期按设备顺序分组)。它几乎做到了,但不完全是。您无法对current_WH进行排名,因为它将按字母顺序排名。我需要按时间对current_WH进行排名。

任何想法如何实现第二张桌子?谢谢你的帮助!

2 个答案:

答案 0 :(得分:1)

我认为这可以满足您的要求

select device,
       max(case when seqnum = 1 then current_wh end) as current_wh,
       max(case when seqnum = 2 then current_wh end) as prev_1_wh,
       max(case when seqnum = 3 then current_wh end) as prev_2_wh,
       max(case when seqnum = 4 then current_wh end) as prev_3_wh
from (select t.*, dense_rank() over (partition by device order by maxdate desc) as seqnum
      from (select t.*, max(date) over (partition by device, current_wh) as maxdate
            from t
           ) t
     ) t
group by device

答案 1 :(得分:0)

这建议我:

select t.device,
       max(case when t.seq = 1 then current_wh end) as current_wh,
       max(case when t.seq = 2 then current_wh end) as prev_1_wh,
       max(case when t.seq = 3 then current_wh end) as prev_2_wh,
       max(case when t.seq = 4 then current_wh end) as prev_3_wh
from (select t.*, dense_rank() over (order by date desc) as seq
      from table t
      where date = (select max(t1.date) from table t1 where t.device = t1.device and t.current_wh = t1.current_wh)
     ) t
group by t.device;