我有这个SQL查询,可以检测到[Type]重复出现。
select Type, count(1) as 'Occurences' from [dbo].[Policy]
where PolicyDescription ='ABC'
group by Type
HAVING COUNT(1)>1
但同一张表[Policy]中也有一列[Id],而我上面的查询没有基于[Id]进行区分。
我希望上述查询仅考虑[Id]也不同的结果。
我应该实施哪些更改?
样本数据
DECLARE @Policy AS TABLE
(
ID int,
PolicyDescription char(3),
Type int
)
INSERT INTO @Policy(ID, PolicyDescription, Type) VALUES
(1, 'ABC', 123),
(1, 'ABC', 123),
(2, 'ABC', 456),
(3, 'ABC', 567),
(4, 'ABC', 567),
(3, 'ABC', 567)
当前结果
Type | Occurences
------|------------
123| 2
567| 3
所需结果
Type | Occurences
------|------------
567| 2
答案 0 :(得分:4)
您可以将COUNT
与DISTINCT
结合使用。
SELECT Type, COUNT(DISTINCT Id) AS 'Occurences'
FROM Policy
WHERE PolicyDescription = 'ABC'
GROUP BY Type
HAVING COUNT(DISTINCT Id) > 1
答案 1 :(得分:0)
您只需要更改:
from policy
收件人:
from (select distinct * from policy)
像这样:
select t.type, count(1) as 'Occurences'
from (select distinct * from policy) t
where t.policydescription ='ABC'
group by t.type
having count(1) > 1
请参见demo