使用SQL Server过滤UNION中的重复项

紧身的

我正在尝试删除由日期值不同引起的重复条目。我试图在分组依据中使用min(date),但这是不允许的

例如,当我需要的只是第一行时,返回以下两行

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
钾盐

您可以将selectwithunion用作临时表,然后select从中使用它,然后执行group by没有DateCreated字段的操作。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

使用SQL Server过滤UNION中的重复项

来自分类Dev

在SQL中的UNION之后删除重复项

来自分类Dev

在SQL Server 2008中删除重复项

来自分类Dev

在SQL Server表中查找重复项

来自分类Dev

SQL Server:使用第一个重复项中的数据更新重复项

来自分类Dev

根据SQL中的组过滤出重复项

来自分类Dev

使用LINQ从类型集合中过滤重复项

来自分类Dev

使用LINQ从类型集合中过滤重复项

来自分类Dev

在SQL Server中两列中查找重复项

来自分类Dev

解决SQL Server中1对多关系中的重复项

来自分类Dev

SQL 中的重复项

来自分类Dev

SQL减少union子句中的重复项

来自分类Dev

在SQL Server的表的nvarchar列中检查重复项

来自分类Dev

左外部Join查询返回SQL Server中的重复项

来自分类Dev

通过SQL Server中的键列删除重复项

来自分类Dev

在SQL Server中检查(并删除)复杂对象重复项

来自分类Dev

在SQL Server的两列中查找重复项

来自分类Dev

在SQL Server中按查询分组返回重复项

来自分类Dev

如何在SQL Server中删除重复项

来自分类Dev

尝试从链接的SQL Server中删除重复项

来自分类Dev

SQL Server:输出重复项

来自分类Dev

SQL过滤器保留重复项

来自分类Dev

SQL-过滤冗余重复项

来自分类Dev

使用对象属性从NSArray过滤重复项

来自分类Dev

使用INSERT INTO时如何过滤重复项

来自分类Dev

使用对象属性从NSArray过滤重复项

来自分类Dev

在sql中检查重复项

来自分类Dev

基于2列从UNION结果中过滤重复项

来自分类Dev

使用SQL重命名Access中的重复项