2014-01-08 2 views
1

제품 가격이 변경되지만 타임 스탬프를 사용하여 가장 최신 정보를 표시하려는 SQL 쿼리를 teradata에서 만들었습니다. 그러나 문제는 데이터에 product_number, price, timestamp가 정확히 반복되어 배수 값을 제공하는 인스턴스가 있다는 것입니다. 나는 그 중복을 제거하기 위해 찾고있다.SQL 타임 스탬프, 중복 행 제거

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를 사용 +

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

당신은 또한 "= 1"또는 것을 함축하고 있다고 할 필요가 없습니다 QUALIFY? – 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

그건 그냥 maxtimestamp가 발생합니다 그것을하고 (모든 열을 포함하여 간단하게 외부 쿼리에 DISTINCT 연산자를 이동하거나 GROUP을 할 수 있어야 오류). 이미 GROUP BY이 있기 때문에

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는 중복입니다.