表格1:
AccountID AccountNumber AccountTypeNumber
1 50 100
2 50 250
3 60 100
4 60 200
表2:
AccountNumber AccountName AccountStatus
50 School Active
60 Work Active
70 School Active
结果表:
AccountNumber AccountVerification
50 Pass
60 Pass
70 Fail
我希望结果表为每个独特的'Pass'
返回'Fail'
/ AccountNumber
结果。 'Pass'
为那些在AccountStatus = Active
有Table2
并且在AccountTypeNumber = 100
有至少一个Table1
的记录。所有其他人,返回'Fail'
。
我目前的结果只显示表1中的AccountNumbers
。它们不包括在AccountNumbers
而不在Table2
的Table1
。
SELECT DISTINCT
Table1.AccountNumber
CASE
WHEN Count (*) OVER (PARTITION BY Table1.AccountNumber) > 1
THEN 'Pass'
ELSE 'Fail'
END AS 'AccountVerification'
FROM Table1
WHERE Table1.AccountTypeNumber = '100'
INNER JOIN Table2 ON Table2.AccountNumber = Table1.AccountNumber
WHERE Table2.AccountStatus = 'Active'
您可以使用带有内联相关子查询的CASE
构造来检查table1
中是否存在相关记录,例如:
SELECT
t2.AccountNumber,
CASE WHEN
t2.AccountStatus = 'Active'
AND EXISTS (
SELECT 1
FROM table1 t1
WHERE t1.AccountNumber = t2.AccountNumber AND t1.AccountTypeNumber=100
)
THEN 'Pass' ELSE 'Fail' END AS AccountVerification
FROM table2 t2
这将正确处理table2
中存在但不存在于table1
中的帐户的用例,并且如果table1
中存在多个匹配记录,也可以避免重复。但是,如果您在table2
中有多次出现的帐号,那么您需要使用DISTINCT
(因为这种情况不会显示在您的示例数据中,我没有使用它,如果需要可以随意添加)。
这个带有样本数据的demo on DB Fiddle返回:
AccountNumber | AccountVerification
------------: | :------------------
50 | Pass
60 | Pass
70 | Fail
从Table2
到Table1
的左连接从Table1
排除where accounttypenumber <> 100
行:
select
t2.accountnumber,
case
when t2.accountstatus = 'Active' and t1.accountnumber is not null then 'Pass'
else 'Fail'
end accountverification
from table2 t2 left join (
select accountnumber from table1
where accounttypenumber = 100
) t1
on t1.accountnumber = t2.accountnumber