[英]Filter Duplicates in UNION with SQL Server
我试图删除由日期值不同引起的重复条目。 我试图在分组中使用min(date),但这是不允许的
例如,当我需要的是第1行时,取回以下2行
MasterCustomerId NewClubKeyId DateAssigned
000000201535 K18752 2014-08-13 20:25:18.717
000000201535 K18752 2015-01-08 00:41:03.037
这是我的查询。 有任何想法吗? 谢谢
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
根据下面@suslov的建议,我按照描述实现了查询,但效果很好。 这里是:
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
您可以将select
with union
用作临时表,然后select
并按照之前没有DateCreated
字段的方式进行group by
。
select t.CreatorMasterCustomerId as MasterCustomerId
, t..NewClubKeyId
, min(t.DateCreated) as DateAssigned
from (<...>) t
group by t.MasterCustomerId
, t.NewClubKeyId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.