如何编写一个case语句,根据一组条件返回一组唯一记录的消息?

问题描述 投票:1回答:2

表格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 = ActiveTable2并且在AccountTypeNumber = 100有至少一个Table1的记录。所有其他人,返回'Fail'

我目前的结果只显示表1中的AccountNumbers。它们不包括在AccountNumbers而不在Table2Table1

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'
sql sql-server
2个回答
2
投票

您可以使用带有内联相关子查询的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               

0
投票

Table2Table1的左连接从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
© www.soinside.com 2019 - 2024. All rights reserved.