2014-03-28 4 views
1

db 값 로그가 있습니다. 때로는 (대개 매월) db에 가격이 저장되는 새로운 주. 각 항목에는 고유 ID가 있습니다. 그것은 매월 바뀌지 않습니다.SQL에서 데이터베이스에 저장된 로그의 변경 사항을 감지합니다.

나는 샘플 데이터베이스를 구축했습니다 :

http://sqlfiddle.com/#!6/0bc28/3

나는 품목 가격의 변화를 감지해야합니다. 예 : 2013-01-01의 item1 가격이 122 일 때 2013-02-01은 122 일, 2013-03-01은 124

선택 표시 1 행 itemname = item1, oldPrice = 122, newPrice = 124, dateCHanged = 2013년 3월 1일

답변

2

이 작동합니다 :

with x as (
    select i.*, s.datecreated, row_number() over (partition by uniqueid order by datecreated) as rn 
    from items i 
    inner join states s on i.stateid = s.id 
) 
select x1.uniqueId, x1.price as oldPrice, x2.price as newPrice, x2.dateCreated as dateChanged 
from x x1 
inner join x x2 on x1.uniqueid = x2.uniqueid 
--and datediff(month, x1.datecreated, x2.datecreated) = 1 
and x1.rn - x2.rn = 1 
and x1.price <> x2.price 
+0

가 나쁘지 않다, 그러나 때때로 그것은 매달 아니다 나는를 고려하여 답을 편집 –

+1

덜 자주 더 오어을 업로드 할 수 있습니다 그 req. – dean

+0

위대해, 고마워. –

관련 문제