在where子句中使用AND和OR

时间:2013-10-30 15:43:15

标签: sql sas

我很难用这个where子句获得正确的结果。我知道这是一个瘫痪问题。有什么建议吗?

WHERE a.EVENT_DATE Between &trend_dt  And &enddate  
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC') 
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)') 
And d.ACTIVE In ('C','F') 
And d.ARCHIVE_STATUS in ('N','Y') 
Or (d.ARCHIVE_STATUS Is Null)

谢谢!

结果的问题是指标2字段有时是空白的,它只返回Indictator 2字段中存在某些内容的记录。

这是查询:

PROC SQL;
CREATE TABLE COMPLAINT_DATA_0 as
SELECT 
a.EVENT_DATE,
a.INDICATOR,
a.INDICATOR2,
a.COMMITTEE_ACTION AS REVIEW_TYPE,
a.LEVEL_OF_EXCEPTION AS METHOD_RECD,
a.REFER_TO AS PLAN_NTWK,
b.DESCRIPTION AS SubCategory, 
d.CROSSREF2 AS ConProvID, 
d.LAST_NAME AS Provider, 
a.MED_REC_NO AS MbrID, 
a.CONFIRMED_BY AS IndProvID, 
a.CODE_15 AS Severity, 
MAX(c.INQUIRY_BODY) AS MaxProcStep, 
e.Notes,
e.Notes2,
FROM VIPDBA.QA_PEER AS a LEFT JOIN VIPDBA.SYS_LOOKUPS AS b 
ON a.INDICATOR2=b.CODE 
LEFT JOIN VIPDBA.QA_PEER_INQUIRY AS c 
     ON a.LOOKUP_KEY=c.LOOKUP_KEY AND 
a.MED_REC_NO=c.MED_REC_NO 
LEFT JOIN VIPDBA.MASTER_CRED AS d 
    ON a.LOOKUP_KEY=d.LOOKUP_KEY 
LEFT JOIN Complaint_Notes AS e 
    ON a.LOOKUP_KEY=e.LOOKUP_KEY AND 
a.MED_REC_NO=e.MbrID
WHERE a.EVENT_DATE Between &trend_dt  And &enddate  
    AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC') 
    And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)') 
    And d.ACTIVE In ('C','F') 
    And 
        ( d.ARCHIVE_STATUS IN ('N','Y') 
        OR d.ARCHIVE_STATUS is null)
GROUP a.EVENT_DATE, 
a.INDICATOR,
a.INDICATOR2,
b.DESCRIPTION, 
d.CROSSREF2, 
d.LAST_NAME, 
a.MED_REC_NO, 
a.CONFIRMED_BY, 
a.CODE_15, 
e.Notes,
e.Notes2,
d.archive_status,
d.active
ORDER BY 
a.EVENT_DATE, 
a.INDICATOR2, 
b.DESCRIPTION, 
d.CROSSREF2, 
d.LAST_NAME

   运行;

4 个答案:

答案 0 :(得分:2)

我认为你正在寻找这个:

WHERE a.EVENT_DATE Between &trend_dt  And &enddate  
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC') 
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)') 
And d.ACTIVE In ('C','F') 
And ( d.ARCHIVE_STATUS in ('N','Y') Or d.ARCHIVE_STATUS Is Null )

使用括号将逻辑组合在一起。

答案 1 :(得分:2)

避免检查NULL(从而避免需要OR ...)的技巧是将NULL转换为可比较的值,如:

WHERE a.EVENT_DATE BETWEEN &trend_dt AND &enddate  
AND a.INDICATOR NOT IN ('INQUIRY (NOS)','PCC') 
AND a.INDICATOR2 NOT IN ('CAT-NA','INQUIRY (NOS)') 
AND d.ACTIVE IN ('C','F') 
AND COALESCE(d.ARCHIVE_STATUS, 'N') IN ('N','Y') 
   ;

答案 2 :(得分:2)

或者您甚至可以避免使用OR :)。

WHERE a.EVENT_DATE Between &trend_dt  And &enddate  
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC') 
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)') 
And d.ACTIVE In ('C','F') 
And COALESCE(d.ARCHIVE_STATUS,'-1') in ('N','Y','-1')

答案 3 :(得分:0)

是否需要查看d.ARCHIVE_STATUS('N','Y')的结果 或者(d.ARCHIVE_STATUS为Null)如果是这样,你可能只需将其改为看起来像这样

WHERE a.EVENT_DATE Between &trend_dt  And &enddate  
AND a.INDICATOR Not In ('INQUIRY (NOS)','PCC') 
And a.INDICATOR2 Not In ('CAT-NA','INQUIRY (NOS)') 
And d.ACTIVE In ('C','F') 
And (
      d.ARCHIVE_STATUS in ('N','Y') 
      Or 
      d.ARCHIVE_STATUS Is Null
    )

这样它只会评估('N','Y')中的d.ARCHIVE_STATUS对d.ARCHIVE_STATUS是否为空