删除基于重复的日期

时间:2016-04-28 14:20:34

标签: sql sql-server

我有以下要选择的查询(将用于更新语句)根据最小服务日期删除重复项并保留最新的svc日期。

select st.SubID, st.RecordNo, st.Fname, st.Lname, st.MemberID,  st.ServiceDate, IsDeduped, DedupCriteria
       from stagingtable st
       join (select MemberID
                     from stagingtable
                     where SubID = 99999
                           and waveseqid = 1
                     group by MemberID
                     having count(*) > 1) st2
       on st.MemberID = st2.MemberID
       and st.ServiceDate = (Select min(ServiceDate) from stagingtable s where s.subid = 99999 and s.waveseqid = 1 and st.MemberID = s.MemberID)
where SubID = 99999
       and waveseqid = 1
       order by RecordNo

这似乎只在某个时间拉动,只有与memberid相同的日期拉数:

SurveyID    RecordNo    Fname   Lname   MemberID    Option9 IsDeduped   DedupCriteria
99999   1   John    Doe 123 10/1/2015   0   NULL x  These show on the query
99999   2   John    Doe 123 10/1/2015   0   NULL x  These show on the query
99999   3   John    Doe 123 10/8/2015   0   NULL But expected these as well
99999   4   John    Doe 123 10/12/2015  0   NULL But expected these as well
99999   4   John    Doe 123 10/14/2015  0   NULL But expected these as well
99999   6   John    Doe 123 10/29/2015  0   NULL But expected these as well
99999   7   John    Doe 123 12/14/2015  0   NULL But expected these as well

1 个答案:

答案 0 :(得分:1)

您的“AND”语句将结果限制为仅包含最短服务日期的行。

and st.ServiceDate = (Select min(ServiceDate) from stagingtable s where s.subid = 99999 and s.waveseqid = 1 and st.MemberID = s.MemberID)

这就是为什么你得到两行而不是全部。