SQL时间戳,消除重复的行

时间:2014-01-08 18:55:02

标签: sql teradata

我在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;

3 个答案:

答案 0 :(得分:3)

只需使用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。

答案 2 :(得分:0)

试试这个

  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 ;