2015-04-28 32 views
0

我需要根據某些條件過濾掉這些數據。Microsoft Access:具有相同ID的多個記錄需要根據特定條件排除

  1. 如果ID有超過1個焦點,那麼我只想保留最新的LastUpdatedDate記錄。
  2. 如果ID具有2個具有相同焦點和相同域的記錄,請保留最新的LastUpdatedDate記錄。
  3. 如果ID具有2個記錄用相同的焦點,但不同的結構域,並且所述階段是3或更大,則保持兩個記錄

下面是示例數據:

ID LastUpdatedbyID Focus Domain Stage LastUpdateDate LastEndorsedDate 
1 1  AT APT 2 3/24/15 10:46 AM 3/24/15 10:46 AM 
1 1  ES ASS 2 3/27/15 10:23 AM 3/27/15 10:23 AM 
1 1  ITC A 2 3/24/15 6:57 AM  3/24/15 6:57 AM 
2 2  BP Fin 2 4/10/15 8:48 AM  4/10/15 8:48 AM 
2 2  BP Fin 3 4/10/15 10:46 AM 4/10/15 12:00 AM 
3 3  ES CS 3 3/16/15 1:56 PM  3/16/15 12:00 AM 
3 3  ES PM 3 3/16/15 1:56 PM  3/16/15 12:00 AM 
3 3  ES PM 1 3/15/15 1:56 PM  3/15/15 2:00 PM 

這裏結果如下:

ID LastUpdatedbyID Focus Domain Stage LastUpdateDate  LastEndorsedDate 
1 1  ES ASS 2 3/27/15 10:23 AM 3/27/15 10:23 AM 
2 2  BP Fin 3 4/10/15 10:46 AM 4/10/15 12:00 AM 
3 3  ES CS 3 3/16/15 1:56 PM  3/16/15 12:00 AM 
3 3  ES PM 3 3/16/15 1:56 PM  3/16/15 12:00 AM 

回答

0

在這個例子中源表稱爲t因此改變其真實姓名。

這個查詢應該給你你想要的結果。基本上三個不同的查詢(每個條件一個)使用聯合運算符組合在一起。我不認爲它表現良好,它可能會得到改善,但使用Access 2010測試它時確實返回了正確結果:

select t.* from t inner join (
    select id, max(LastUpdateDate) as aLastUpdateDate 
    from t 
    where id not in (select id from t group by id,focus, Domain having count(*) > 1) 
    and id not in (select id from t where stage >= 3 group by id,focus having count(domain) > 1) 
    group by id having count(focus) > 1 
) a on a.ID = t.id and a.aLastUpdateDate = t.LastUpdateDate 

union all 

select t.* from t inner join (
    select id, focus, Domain, max(LastUpdateDate) as bLastUpdateDate 
    from t 
    group by id,focus, Domain 
    having count(*) > 1 
) b on b.ID=t.ID and b.Focus = t.Focus and b.Domain=t.Domain and b.bLastUpdateDate = t.LastUpdateDate 

union all 

select t.* from t inner join (
    select id, focus, stage 
    from t 
    where stage >= 3 
    group by id,focus, stage 
    having count(domain) > 1 
) c on c.ID=t.ID and c.Focus = t.Focus and c.stage = t.stage 
+0

您的前2個select語句的功能正確第三個select語句在我的實際數據集中返回了一行,我並不期待。我編輯了我的原始問題,並在我的示例數據中添加了最後一行。出於某種原因,它返回了我的數據集中的那一行。任何想法發生了什麼? – Kmart6700

+0

@ Kmart6700我認爲我犯了一個錯誤。最後的查詢應該也可能包含舞臺。我會更新答案。請立即嘗試一下。 – jpw

+1

工作。謝謝。 – Kmart6700

相關問題