Sql 如何编写case语句,根据一组条件为一组唯一的记录返回消息?
表1: 表2:Sql 如何编写case语句,根据一组条件为一组唯一的记录返回消息?,sql,sql-server,tsql,join,select,Sql,Sql Server,Tsql,Join,Select,表1: 表2: AccountID AccountNumber AccountTypeNumber 1 50 100 2 50 250 3 60 100 4 60 200 结果表: AccountNumber AccountName AccountStatus 50 School Ac
AccountID AccountNumber AccountTypeNumber
1 50 100
2 50 250
3 60 100
4 60 200
结果表:
AccountNumber AccountName AccountStatus
50 School Active
60 Work Active
70 School Active
我希望结果表为每个唯一的AccountNumber返回“通过”/“失败”结果。”表2中AccountStatus=Active且表1中至少有一条AccountTypeNumber=100的记录,则为“通过”。所有其他,返回“失败”
我目前的结果仅显示表1中的帐号。它们不包括表2和表1中的帐号
您可以使用带有内联相关子查询的CASE构造来检查表1中是否存在相关记录,如:
这将正确处理一个帐户存在于表2中而不存在于表1中的用例,并且如果表1中有多个匹配记录,也可以避免重复。但是,如果您的帐号在表2中出现了不止一次,那么您需要使用DISTINCT,因为这种情况不会出现在您的示例数据中,我没有使用它,如果需要,请随意添加它
这与您的示例数据一起返回:
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
使用表2到表1的左连接,不包括表1中accounttypenumber为100的行:
表1中是否有不在表2中的帐号?谢谢。表2中有重复的帐号,结果似乎不正确。它显示AccountTypeNumber=100且AccountStatus=active的几个AccountNumber的“失败”。当我需要包含其他字段时,如何添加Distinct?选择AccountName,AccountUniqueID,DISTINCT t2.AccountNumber,当t2.AccountStatus='Active'且存在时,从表1 t1中选择1,其中t1.AccountNumber=t2.AccountNumber和t1.AccountTypeNumber=100,然后…@SLM:只需将«选择»替换为«选择DISTINCT»,就这些。让我知道它是否有效。。。
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'
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
AccountNumber | AccountVerification
------------: | :------------------
50 | Pass
60 | Pass
70 | Fail
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