【问题标题】:Count Duplicates from a union all Query从联合所有查询中计算重复项
【发布时间】:2018-08-01 10:35:15
【问题描述】:

尝试从联合所有查询中计算重复项。如果我添加一个组,它会消除重复项。我需要计算两个帐户中的两个重复项,但该帐户中可能有我不关心的重复项。因此独特的

Select CRID.CId as CIds FROM
(
    Select Distinct([CId]) as CId From [dbo].[MyTable] Where AccountId = 'E7888A78-043F-4C34-BB72-1EDC97D32EDB'
    UNION ALL
    Select Distinct([CId]) as CId From [dbo].[MyTable] Where AccountId = 'CC94E667-7776-4427-A6D9-6492C5CDA617'
) CRID
Having Count(CRID.CId > 1) -- Can't use having

【问题讨论】:

  • 执行 row_number() 并计算 1 以上有多少

标签: sql sql-server


【解决方案1】:

因为你只有两张桌子,你可以这样做:

select count(*) - count(distinct cid) as num_duplicates
from ((Select Distinct([CId]) as CId 
       from [dbo].[MyTable]
       Where AccountId = 'E7888A78-043F-4C34-BB72-1EDC97D32EDB'
      ) union all
      (Select Distinct([CId]) as CId
       from [dbo].[MyTable]
       Where AccountId = 'CC94E667-7776-4427-A6D9-6492C5CDA617'
      )
     ) CRID;

但是,您似乎想要同时具有AccountIds 的Cids。我只会去:

select cid
from dbo.MyTable
where AccountId in ('E7888A78-043F-4C34-BB72-1EDC97D32EDB', 'CC94E667-7776-4427-A6D9-6492C5CDA617')
group by cid
having count(distinct AccountId) > 1;

如果您想要计数,请使用子查询:

select count(*)
from (select cid
      from dbo.MyTable
      where AccountId in ('E7888A78-043F-4C34-BB72-1EDC97D32EDB', 'CC94E667-7776-4427-A6D9-6492C5CDA617')
      group by cid
      having count(distinct AccountId) > 1
     ) t;

【讨论】:

  • 感谢您的快速回复。选项3是完美的。如果你有时间回答,为什么不只计算选项 2 的结果会产生与 3 相同的结果。我检查过,我知道它不只是不知道为什么。感谢 select count(cid) from dbo.MyTable where AccountId in ('E7888A78-043F-4C34-BB72-1EDC97D32EDB', 'CC94E667-7776-4427-A6D9-6492C5CDA617') group by cid with count(distinct AccountId) > 1;
猜你喜欢
  • 2012-09-06
  • 1970-01-01
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 1970-01-01
  • 2016-07-21
相关资源
最近更新 更多