简体   繁体   中英

Filter Duplicates in UNION with SQL Server

I am trying to remove the duplicate entries which are being caused by date values being different. I tried to use min(date) in group by but that's not allowed

For example in getting back the following 2 rows when all I need is the 1st

MasterCustomerId    NewClubKeyId    DateAssigned
000000201535        K18752          2014-08-13 20:25:18.717
000000201535        K18752          2015-01-08 00:41:03.037

Here is my query. Any ideas? Thanks

SELECT  nc.CreatorMasterCustomerId MasterCustomerId,nc.NewClubKeyId,MIN(nc.DateCreated) DateAssigned
FROM NewClub nc
WHERE nc.IsActive = 1 AND nc.NewClubKeyId IS NOT NULL AND nc.DateCreated IS NOT NULL
AND nc.DateCreated >='2013-10-10'
GROUP BY nc.CreatorMasterCustomerId,nc.NewClubKeyId,nc.DateCreated

UNION

SELECT   ncb.MasterCustomerId,nc.NewClubKeyId,MIN(ncb.DateCreated) DateAssigned
FROM NewClubBuilder ncb
JOIN NewClub nc ON nc.Id = ncb.NewClubId
WHERE nc.IsActive = 1 AND nc.NewClubKeyId IS NOT NULL AND ncb.DateCreated IS NOT NULL
AND ncb.DateCreated >='2013-10-10'
GROUP BY ncb.MasterCustomerId,nc.NewClubKeyId,ncb.DateCreated

Per the suggestion from @suslov below, I implemented the query as described and it works well. Here it is:

select 
t.MasterCustomerId,
t.NewClubKeyId,
MIN(t.DateCreated)DateAssigned
FROM
(
    SELECT DISTINCT nc.CreatorMasterCustomerId MasterCustomerId,nc.NewClubKeyId,nc.DateCreated
    FROM NewClub nc
    WHERE nc.IsActive = 1 AND nc.NewClubKeyId IS NOT NULL AND nc.DateCreated IS NOT NULL
    AND nc.DateCreated >='2013-10-10'

    UNION

    SELECT DISTINCT  ncb.MasterCustomerId,nc.NewClubKeyId,ncb.DateCreated
    FROM NewClubBuilder ncb
    JOIN NewClub nc ON nc.Id = ncb.NewClubId
    WHERE nc.IsActive = 1 AND nc.NewClubKeyId IS NOT NULL AND ncb.DateCreated IS NOT NULL
    AND ncb.DateCreated >='2013-10-10'
)t

GROUP BY t.MasterCustomerId,t.NewClubKeyId

You can use your select with union as a temporary table and then select from it and do a group by you did before without DateCreated field.

select t.CreatorMasterCustomerId as MasterCustomerId
     , t..NewClubKeyId
     , min(t.DateCreated) as DateAssigned
from (<...>) t
group by t.MasterCustomerId
       , t.NewClubKeyId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM