看板 Database 關於我們 聯絡資訊
※ 引述《seabok (思念,留在1999)》之銘言: : 資料庫名稱:MS SQL : 資料庫版本:2008 : 內容/問題描述: : 請問各位賢拜: : 有一Table A如下: : ID UPDate OldValue NewValue : 001 2016/3/24 AAA BBB : 002 2016/3/23 CCC DDD : 002 2016/3/24 DDD CCC : 需求是想撈出在日期區間內有異動的資料,也就是最終的OldValue <> NewValue。 : 可是在表中第2、3列,ID=002的資料在3/23先是自CCC改成DDD, : 然後在3/24又自DDD改回CCC,最終結果其實是沒有異動。 : 請問SQL該如何下才能直接排除這種情形呢?(也就是只有ID=001這筆符合) : 先感謝大家了~ with tb1 as (select ROW_NUMBER() over(partition by id order by [update]) as num,* from table_1 where [update] between '2016/3/23' and '2016/3/24') ,tb2 as (select ROW_NUMBER() over(partition by id order by [update] desc) as num,* from table_1 where [update] between '2016/3/23' and '2016/3/24') select * from tb1 a inner join tb2 b on a.ID=b.ID where a.num=1 and b.num=1 and a.OldValue<>b.NewValue -- Sent from my Windows -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.34.194.8 ※ 文章網址: https://www.ptt.cc/bbs/Database/M.1458828881.A.DF0.html
cutekid: 推(Y) 03/25 13:31