SQL-如何在列中获取唯一值(在这里,distinct没有帮助)

SQL-如何在列中获取唯一值(在这里,distinct没有帮助),sql,distinct,rank,presto,Sql,Distinct,Rank,Presto,我有一个生产案例,我们跟踪在仓库中移动的设备。我有一张表格,上面显示了这些以前的位置,如下所示: +--------+------------+-----------+------+ | device | current_WH | date | rank | +--------+------------+-----------+------+ | 1 | AB | 3/15/2018 | 7 | | 1 | CC | 3/19/

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

+--------+------------+-----------+------+
| 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 |
+--------+------------+-----------+------+
但我需要找到当前_WH的唯一值,并将设备缩减为一行(有数百万台设备),如下所示:

+--------+------------+--------+--------+--------+
| device | current_WH | prev_1 | prev_2 | prev_3 |
+--------+------------+--------+--------+--------+
|      1 | AA         | DD     | CC     | AB     |
+--------+------------+--------+--------+--------+
我使用了rank函数(按设备分组,按日期排序)。它几乎做到了,但不完全做到。您不能对当前的\u WH排序,因为它将按字母顺序排序。我需要按时间排列当前的位置


你知道如何实现第二个表格吗?谢谢你的帮助

我想这正是你想要的:

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
这让我想到:

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;

你试过什么?让我们看看你的尝试。我像这样尝试,达到了第一个表。从表中按设备顺序、日期选择设备、当前\u WH、日期、稠密\u rank()(按设备划分\u id顺序按开发日期描述)rnk;哼哼……我输入了硬回报,以便于阅读;不知道为什么它不显示,太神奇了。我不得不将“按maxdate订购”改为“按maxdate描述订购”,谢谢!谢谢你的意见,但它似乎不起作用。我得到一些值和很多空值。