Microsoft Access:具有相同ID的多个记录需要基于某些条件进行排除

时间:2015-04-28 19:09:41

标签: sql ms-access

我需要根据某些标准过滤掉这些数据。

  1. 如果ID超过1个Focus,那么我只想保留最新的LastUpdatedDate记录。
  2. 如果ID具有2个具有相同焦点和相同域的记录,请保留最新的LastUpdatedDate记录。
  3. 如果ID具有2个具有相同焦点但具有不同域的记录,并且阶段为3或更大,则保留两个记录
  4. 以下是示例数据:

    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
    

1 个答案:

答案 0 :(得分:0)

在此示例中,源表名为t,因此请更改为其真实姓名。

此查询应该为您提供所需的结果。它基本上是使用union运算符组合的三个不同的查询(每个条件一个)。我不认为它表现那么好并且它可能会得到改进,但是当我使用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