查询中多个 CASE 语句和 ISNULL() 函数的语法

Syntax for multiple CASE statements and ISNULL() functions in a query

我被同事发给我的这个简单问题难住了。

虽然我从逻辑的角度理解他试图做的事情,但我仍然停留在语法上。这真的很烦我。我在阅读过的任何文档中都没有真正找到类似的内容。以下是他的消息和最相关的代码块:


Hey (TRose), here is a tough one to think on. This is a mssql query and I have it currently hiding ‘inactive’ parties when I select it as a parameter but I left out ‘dismissed’ and need to add it in to the statement to act just the same as ‘inactive’:

SELECT
CaseName = justice.dbo.fnFormatFullNameFMLSByNameID(cp.nameid),
CurrentKnownName = justice.dbo.fnFormatFullNameFMLSByPartyID(cp.partyid),
CasePartyAtty =  justice.dbo.fnCasePartyLeadAttorney(cp.caseid,cp.partyid),
cpc.casepartyconnid,
PartyActive = (select top 1  case isnull(inactive ,0)
when 0 then 'YES'
else 'NO'
end
from justice.dbo.CasePartyConnStat cps
where cps.CasePartyConnID = cpc.CasePartyConnID
order by cps.CasePartyConnStatID desc)
FROM  justice.dbo.ClkCaseHdr ct 
when 'OP' then '53OP'
when 'PA' then '53PA'
join justice.dbo.CaseAssignHist cah on cah.CaseAssignmentHistoryID = ct.CaseAssignmentHistoryIDCur
join justice.dbo.CaseParty cp on cp.caseid = ct.caseid
join justice.dbo.CasePartyConn cpc on cpc.CasePartyId = cp.casePartyid 
and BaseConnKy not in ('AT') 
WHERE ct.caseid = @CaseID

我在 SQL 还不错,但我就是不知道这个问题的答案。 SQLFiddle 没有帮助,因为我没有可用的架构信息。这是严格的语法。

感谢我能得到的任何帮助。

首先,这不需要子查询:

PartyActive = (select top 1  case isnull(inactive ,0)
when 0 then 'YES'
else 'NO'
end

只需使用并明确逻辑:

PartyActive = (case when inactive = 0 or inactive is null then 'YES'
                    else 'NO'
               end)

根据实际逻辑("and" 或 "or"),您可以这样做:

PartyActive = (case when inactive = 0 or inactive is null then 'YES'
                    when dismissed = 0 or dismissed is null then 'YES'
                    else 'NO'
               end)

这实现了逻辑,如果某物不是非活动的且未被关闭,则表示它是活动的。