自我加入带来了太多记录

时间:2013-03-20 17:14:13

标签: sql sql-server-2005 inner-join self-join

我有这个查询来表达一组业务规则。 为了获得我需要的信息,我尝试自己加入表,但这会带来比实际表中更多的记录。以下是我试过的查询。我做错了什么?

SELECT DISTINCT a.rep_id, a.rep_name, count(*) AS 'Single Practitioner'
FROM [SE_Violation_Detection] a inner join [SE_Violation_Detection] b 
ON a.rep_id = b.rep_id and a.hcp_cid = b.hcp_cid
group by a.rep_id, a.rep_name
having count(*) >= 2

2 个答案:

答案 0 :(得分:4)

您可以使用having子句完成此操作:

select a, b, count(*) c
from etc
group by a, b
having count(*) >= some number

答案 1 :(得分:1)

我找到了一种更简单的方法来获取其中一个查询所需的信息。上面的问题仍然是错误的。

--Rep violation for different HCP more than 5 times 
select distinct rep_id,rep_name,count(distinct hcp_cid) 
AS 'Multiple Practitioners' 
from dbo.SE_Violation_Detection
group by rep_id,rep_name 
having count(distinct hcp_cid)>4 
order by count(distinct hcp_cid)