在where子句中使用IF逻辑

时间:2012-06-12 01:25:12

标签: sql-server-2005 if-statement case-when

好的,在提出这个问题之前,我已经对这个主题进行了大量的研究,但是考虑到我的具体情况。目前我的代码如下所示:

SELECT RTRIM(logtype)+'-'+RTRIM(servicenbr)+'-'+CONVERT(varchar(25), idserv) as CaseNbr, (CASE WHEN tn.TeamText IS NULL THEN 'HELPDESK' WHEN tn.TeamText like '' THEN 'HELPDESK' ELSE tn.TeamText END) as SourceTeam, (tn2.TeamText) as DestinationTeam
 FROM teamnames as tn2
    LEFT OUTER JOIN caseaudit AS ca
    ON tn2.teamID = ca.referteamID2
    LEFT OUTER JOIN openstatus As os
    ON ca.logno = os.logno
    LEFT OUTER JOIN teamnames as tn
    ON ca.referteamid1 = tn.teamid
 WHERE CONVERT(smalldatetime,ca.dModLast,101) BETWEEN '2012-06-04' AND '2012-06-11'

 --NEED TO PUT IF CLAUSE HERE

 ORDER BY DestinationTeam

具体来说,我的IF子句或CASE WHEN需要测试才能看到

WHERE ca.asggrp1 <> ca.asggrp2 
AND ca.referteamid1 <> ca.referteamid2 AND tn2.isactive = 1 AND tn2.groupid = 18. 

If they are equal, then the ticket should be ignored UNLESS 
ca.asggrp1 = 'CLIENT' AND ca.asggrp2 = 'CLIENT' 
AND ca.referteamid1 <> ca.referteamid2 AND tn2.isactive = 1 AND tn2.groupid = 18.

编辑:

好吧......让我们试一试。查询应始终提取具有限制的案例:

WHERE ca.referteamid1 <> ca.referteamid2 AND tn2.isactive = 1 AND tn2.groupid = 18

另外,我想将结果限制在ca.asggrp1 <> ca.asggrp2时,除非它们都等于'客户'

修改

再试一次......我失去了观众。这是我能给出的最好的解释。

SELECT RTRIM(logtype)+'-'+RTRIM(servicenbr)+'-'+CONVERT(varchar(25), idserv) as CaseNbr, (CASE WHEN tn.TeamText IS NULL THEN 'HELPDESK' WHEN tn.TeamText like '' THEN 'HELPDESK' ELSE tn.TeamText END) as SourceTeam, (tn2.TeamText) as DestinationTeam
 FROM teamnames as tn2
    LEFT OUTER JOIN caseaudit AS ca
    ON tn2.teamID = ca.referteamID2
    LEFT OUTER JOIN openstatus As os
    ON ca.logno = os.logno
    LEFT OUTER JOIN teamnames as tn
    ON ca.referteamid1 = tn.teamid
 WHERE CONVERT(smalldatetime,ca.dModLast,101) BETWEEN '2012-06-04' AND '2012-06-11'
 AND ca.referteamid1 <> ca.referteamid2 AND tn2.isactive = 1 AND tn2.groupid = 18
----AND (ca.asggrp1 <> ca.asggrp2 UNLESS ca.asggrp1 = 'CLIENT' AND ca.asggrp2 = 'CLIENT')
 ORDER BY DestinationTeam

1 个答案:

答案 0 :(得分:1)

我觉得自己像个白痴。我只需要使用一个简单的OR。

AND (ca.asggrp1 <> ca.asggrp2 OR ca.asggrp1 = 'CLIENT' AND ca.asggrp2 = 'CLIENT')

我想我们一次又一次地复杂化了。