带条件的WHERE子句

时间:2012-08-16 10:44:49

标签: sql

好的,这是问题,

   SELECT CTE.TECHNICIANID, SUM(TLEVEL) AS TLEVEL, TECH.PASSEDDRUGTEST, TECH.PASSEDBACKGROUNGCHECK, TECH.FIRSTNAME, TECH.LASTNAME, 
        CM.CITYID, CM.ADDRESS, CM.EMAIL, CM.PHONENUMBER, CM.ZIPCODE, CNTRY.COUNTRYNAME, SM.STATENAME,
         CM.LATITUDE, CM.LONGITUDE FROM CTE
        INNER JOIN TECHNICIAN TECH ON CTE.TECHNICIANID = TECH.TECHNICIANID 
        INNER JOIN SERVICEORDER SO ON SO.SERVICEORDERID = @SERVICEORDERID
        INNER JOIN CONTRACT CONT ON SO.CONTRACTID = CONT.CONTRACTID
        INNER JOIN CONTACTMASTER CM ON CM.CONTACTID = TECH.CONTACTID
        INNER JOIN COUNTRYMASTER CNTRY ON CM.COUNTRYID = CNTRY.COUNTRYID
        INNER JOIN STATEMASTER SM ON SM.STATEID = CM.STATEID
        --WHERE CONT.DRUGSCREENINGREQUIRED = CASE CONT.DRUGSCREENINGREQUIRED  WHEN 'TRUE' THEN TECH.PASSEDDRUGTEST END AND
        --CONT.BACKGROUNDCHECKREQUIRED = CASE CONT.BACKGROUNDCHECKREQUIRED WHEN 'TRUE' THEN TECH.PASSEDBACKGROUNGCHECK END
        GROUP BY CTE.TECHNICIANID, TECH.PASSEDDRUGTEST, TECH.PASSEDBACKGROUNGCHECK,CM.LATITUDE, TECH.FIRSTNAME, TECH.LASTNAME, 
        CM.CITYID, CM.ADDRESS, CM.EMAIL, CM.PHONENUMBER, CM.ZIPCODE, CNTRY.COUNTRYNAME, SM.STATENAME, CM.LONGITUDE ORDER BY TLEVEL DESC

使用where子句查看查询中的注释部分,当需要drugscreeningtrue时,我想要的是我想要passeddrugtesttrue的所有记录否则我不想申请任何条件

修改:当CONT.DRUGSCREENINGREQUIREDCONT.BACKGROUNDCHECKREQUIRED为真时,我只想使用TECH.PASSEDDRUGTESTTECH.PASSEDBACKGROUNGCHECK过滤记录。如果它们不是真的,我想要所有记录,无论TECH.PASSEDDRUGTESTTECH.PASSEDBACKGROUNGCHECK是真还是假。

2 个答案:

答案 0 :(得分:0)

也许我误解了这个问题,但你能不能这样做吗?

WHERE CONT.DRUGSCREENINGREQUIRED = 'FALSE' OR CONT.DRUGSCREENINGREQUIRED = 'TRUE' AND TECH.PASSEDDRUGTEST = 'TRUE'

答案 1 :(得分:0)

如果这些标志是独立的(与问题相反,但在我看来应该如此),您可能会检索不需要检查或检查通过的记录,简而言之如下:

WHERE (CONT.DRUGSCREENINGREQUIRED = 'FALSE' OR TECH.PASSEDDRUGTEST = 'TRUE')
  AND (CONT.BACKGROUNDCHECKREQUIRED = 'FALSE' OR TECH.PASSEDBACKGROUNGCHECK = 'TRUE')

如果你真的想检查passed状态是否有两个标志,那么你可以使用这个模式:

WHERE (    CONT.DRUGSCREENINGREQUIRED = 'FALSE' 
        OR CONT.BACKGROUNDCHECKREQUIRED = 'FALSE'
        OR (     TECH.PASSEDDRUGTEST = 'TRUE' 
             AND TECH.PASSEDBACKGROUNGCHECK = 'TRUE'
           )
      )