【问题标题】:SQL - how to get unique values in a column (distinct does not help here)SQL - 如何在列中获取唯一值(不同在这里没有帮助)
【发布时间】:2018-08-16 12:56:23
【问题描述】:

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

+--------+------------+-----------+------+
| 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 进行排名。

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

【问题讨论】:

  • 你试过什么?向我们展示你的尝试。
  • 我这样试过,实现了第一张表。 select device, current_WH, date, dense_rank() over(partition by device_id order by devev_day desc) rnk from table order by device, date;
  • 嗯.....我输入了硬回报以使其更易于阅读;不知道为什么它不显示。

标签: sql distinct rank presto


【解决方案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

【讨论】:

  • 太棒了。我只需要将“按 maxdate 排序”更改为“按 maxdate desc 排序”谢谢!
【解决方案2】:

这建议我:

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;

【讨论】:

  • 感谢您的意见,但它似乎不起作用。我得到了一些值和很多空值。
猜你喜欢
  • 2021-03-24
  • 2023-03-19
  • 2014-11-26
  • 2011-05-23
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多