【问题标题】:SQL timestamp, eliminate duplicate rowsSQL时间戳,消除重复行
【发布时间】:2014-01-09 08:35:03
【问题描述】:

我在 teradata 中创建了一个 SQL 查询,该查询在产品价格发生变化时,但想要显示最新的 - 使用时间戳。然而,问题是数据确实存在 product_number、price、timestamp 精确重复的实例,给出了多个值。我正在寻找消除这些重复项。

 select a.product_number, a.maxtimestamp, b.product_price
 from    ( SELECT DISTINCT product_number ,MAX(update_timestamp) as maxtimestamp
 FROM product_price
 group by product_number) a
 inner join product_price b on a.product_number = b.product_number 
and a.maxtimestamp =   b.update_timestamp;

【问题讨论】:

    标签: sql teradata


    【解决方案1】:

    只需使用 ROW_NUMBER + QUALIFY

    select *
    from product_price
    qualify
       row_number() 
       over (partition by product_number
             order by update_timestamp desc) = 1;
    

    【讨论】:

    • 你不需要说“=1”还是暗示?
    【解决方案2】:

    您应该能够简单地将您的 DISTINCT 运算符移动到外部查询,或者执行一个覆盖所有列的 GROUP BY(仅在 maxtimestamp 上执行此操作会导致错误)。

     select DISTINCT a.product_number, a.maxtimestamp, b.product_price
     from    ( SELECT product_number ,MAX(update_timestamp) as maxtimestamp
     FROM product_price
     group by product_number) a
     inner join product_price b on a.product_number = b.product_number 
     and a.maxtimestamp =   b.update_timestamp
    

     select a.product_number, a.maxtimestamp, b.product_price
     from    ( SELECT DISTINCT product_number ,MAX(update_timestamp) as maxtimestamp
     FROM product_price
     group by product_number) a
     inner join product_price b on a.product_number = b.product_number 
     and a.maxtimestamp =   b.update_timestamp
     GROUP BY a.product_number, a.maxtimestamp, b.product_price
    

    顺便说一句,内部子查询中的 DISTINCT 是多余的,因为您已经有一个 GROUP BY。

    【讨论】:

      【解决方案3】:

      试试这个

        select a.product_number, a.maxtimestamp, b.product_price
        from    ( SELECT DISTINCT product_number ,MAX(update_timestamp) as maxtimestamp
        FROM product_price
        group by product_number) a
        inner join product_price b on a.product_number = b.product_number 
        and a.maxtimestamp =   b.update_timestamp
        group by maxtimestamp ;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-03
        • 2021-12-14
        • 2022-10-14
        • 1970-01-01
        • 1970-01-01
        • 2013-08-22
        • 2021-11-15
        • 2018-08-09
        相关资源
        最近更新 更多