Link to home
Start Free TrialLog in
Avatar of printmedia
printmedia

asked on

Subquery count being doubled

Hi all.

I have the following query that contains a subquery. I want to only display records whose count (from the subquery) is greater than 1.

The problem is that the count it's displaying is twice as many as the original count. So for example, it's showing record ABC as having a count of 4, when in reality the count is 2. When I use the subquery (SQ) as it's own query it correctly shows a count of 2, but when I add it to the query below (as a subquery) it doubles the count. What am I doing wrong?

SELECT DISTINCT a.GPOContractID, b.EntityCode, COUNT(SQ.EntityCode) AS Count
FROM         ContractAssignmentHeader AS a INNER JOIN
                      ContractAssignmentDetail AS b ON a.CANumber = b.CANumber INNER JOIN
                          (SELECT DISTINCT ContractAssignmentHeader.CANumber, ContractAssignmentHeader.GPOContractID, ContractAssignmentDetail.EntityCode
                            FROM          ContractAssignmentHeader INNER JOIN
                                                   ContractAssignmentDetail ON ContractAssignmentHeader.CANumber = ContractAssignmentDetail.CANumber
                            WHERE      (ContractAssignmentDetail.Status = N'Active') AND (ContractAssignmentHeader.ContractType = N'GPO')) AS SQ ON 
                      a.GPOContractID = SQ.GPOContractID AND b.EntityCode = SQ.EntityCode
GROUP BY a.GPOContractID, b.EntityCode
HAVING     (COUNT(SQ.EntityCode) > 1)
ORDER BY a.GPOContractID

Open in new window


Thank you in advance.
ASKER CERTIFIED SOLUTION
Avatar of Mark Wills
Mark Wills
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of printmedia
printmedia

ASKER

Thank you for explaining it in detail! Removing the DISTINCT made the query even faster. Thank you!