计算来自联合所有查询的重复项

时间:2018-08-01 10:35:15

标签: sql sql-server

尝试计算重复项形成一个并集所有查询。如果我添加一个组,则消除重复项。我需要计算两个帐户中的两个重复项,但是该帐户中可能有重复项,即时消息无关。因此与众不同

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

1 个答案:

答案 0 :(得分: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;

但是,您似乎想要同时具有Cid的{​​{1}}个。我只想去找

AccountId

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

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;