2014-01-08 2 views
1

Я создал SQL-запрос в teradata, который при изменении цены продукта, но хочет показать наиболее обновленное - используя метку времени. Однако проблема состоит в том, что у данных есть экземпляры, где точно обозначена метка product_number, price, timestamp, дающая многозначные значения. Я ищу, чтобы устранить эти дубликаты.SQL 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

Просто используйте ROW_NUMBER + QUALIFY

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

Вы не должны также сказать, "= 1" или что подразумевается? – BellevueBob

+0

Конечно, ты прав. Модифицированный мой ответ, спасибо. – dnoeth

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

Как и в сторону, неповторяющиеся во внутреннем подзапроса является излишним, поскольку у вас уже есть GROUP BY.

Смежные вопросы