我有以下两个选择:
Declare @S_PWO varchar(300)
Declare @S_O varchar(300)
@S_PWO =
(
SELECT COUNT(PWO.Attr1)
FROM Person P
JOIN PersonInOrg PIO
ON P.UID_Person = PIO.UID_Person
JOIN Org O
ON O.UID_Org = PIO.UID_Org
JOIN PersonWantsOrg PWO
ON PIO.Attr2 = PWO.Attr3
WHERE
O.Attr4 like '%STRING%' AND
P.UID_Person = 'XXXXXXXXX'
)
@S_O =
(
SELECT Count(O.CCC_DisplayName)
FROM Person P
JOIN PersonInOrg PIO
ON P.UID_Person = PIO.UID_Person
JOIN Org O
ON O.UID_Org = PIO.UID_Org
JOIN PersonWantsOrg PWO
ON PIO.Attr2 = PWO.Attr3
WHERE
O.Attr4 like '%STRING%' AND
P.UID_Person = 'XXXXXXXXX'
)
对于XXXXXXXXX人,他们的计数可能相等,也可能不相等。 现在,我需要找到所有这两个Select都不正确的人。 我该怎么办?
答案 0 :(得分:1)
您在两个选择中使用相同的Join / Where,只有Count不同。
将两者简单地组合成一个分组方式,UID_Person
并应用Having
:
SELECT P.UID_Person, Count(PWO.Attr1) AS cntAttr1, Count(O.CCC_DisplayName) AS cntDisplayName
FROM Person P
JOIN PersonInOrg PIO
JOIN PersonInOrg PIO
ON P.UID_Person = PIO.UID_Person
JOIN Org O
ON O.UID_Org = PIO.UID_Org
JOIN PersonWantsOrg PWO
ON PIO.Attr2 = PWO.Attr3
WHERE
O.Attr4 LIKE '%STRING%'
GROUP BY P.UID_Person
HAVING Count(PWO.Attr1) <> Count(O.CCC_DisplayName)