【问题标题】:How to partition and find the most latest value in SQL如何在 SQL 中分区并找到最新的值
【发布时间】:2020-06-15 06:51:57
【问题描述】:

我有一张如下表:

ID   | col1 | Date Time
1    | WA   | 2/11/20
1    | CI   | 1/11/20
2    | CI   | 2/11/20
2    | WA   | 3/11/20
3    | WA   | 2/10/20
3    | WA   | 1/11/20
3    | WA   | 2/11/20
4    | WA   | 1/10/20
4    | CI   | 2/10/20
4    | SA   | 3/10/20

我想查找 col1 除了 WA 之外还有其他值的所有 ID 值,并且 col1 中的最新值应该是“WA”。即从上面的示例数据中,应该只返回 ID 值 1 和 2。因为这两者除了 WA 之外还有一个附加值(即 CI),但它们的最新值仍然是 WA。

我如何得到它??

仅供参考,可能有些 ID 根本没有 WA 值。我想消灭它们。还有那些只有WA值的,我也想去掉。

感谢您的帮助。

【问题讨论】:

    标签: sql amazon-redshift partition database-partitioning


    【解决方案1】:

    您可以为此使用窗口函数:

    select distinct id
    from (
        select 
            t.*,
            last_value(col1) over(partition by id oder by datetime) last_col1,
            min(col1) over(partition by id) min_col1,
            max(col1) over(partition by id) max_col1
        from mytable t
    ) t
    where last_col1 = 'WA' and min_col1 <> max_col1
    

    内部查询使用last_value() 恢复给定col1 的last 值id,并计算同一分区中的最小值和最大值。

    然后,外部查询过滤ids,其最后一个值为'WA',并且至少有两个不同的值(这被表述为最小值和最大值的不等式)。

    【讨论】:

      【解决方案2】:

      您可以通过聚合来做到这一点:

      select id
      from t
      group by id
      having min(col1) <> max(col1) and -- at least two different values
             max(case when col1 = 'WA' then datetime end) = max(datetime)   -- last is WA
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-02
        • 1970-01-01
        • 2018-03-04
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 1970-01-01
        • 2021-12-29
        相关资源
        最近更新 更多