使用多个案例陈述加入多个条件

时间:2014-09-17 20:46:19

标签: sql sql-server tsql

我正在加入:

SELECT COLUMNA,COLUMNB..
FROM MYTABLE
JOIN ON
A1.B = B1.B
AND A1.C = B1.C
AND [JOIN ON SOME_CLAUSE1 AND SOME_CLAUSE2 ONLY IF CERTAIN CONDITIONS ARE MET]

换句话说,如果不符合“某些条件”,我只想加入:

A1.B = B1.B
AND A1.C = B1.C

我该怎么做?

这是我的非伪代码:

SELECT * 
FROM   my TABLE 
JOIN 
on     Onyx.iownerid = mscrm.fi_id.search 
AND    onyx.question = mscrm.question 
AND    onyx.response = 
       CASE 
              WHEN onyx.questiontype IN (1,2) THEN 
                     CASE 
                            WHEN onyx.questiontype=2 THEN mscrm.answer 
                            WHEN onyx.questiontype=1 THEN 
                                   ( 
                                          SELECT TOP 1 
                                                 vchparameterdesc 
                                          FROM   db..referenceparameters 
                                          WHERE  iparameterid=mscrm.answer) 
                     END 
       END

1 个答案:

答案 0 :(得分:3)

伪问题的伪答案:

SELECT COLUMNA,COLUMNB..
FROM MYTABLE
JOIN ON
A1.B = B1.B
AND A1.C = B1.C
AND (
  CertainConditions = 'false'
  OR (SOME_CLAUSE1 AND SOME_CLAUSE2)
)

(OP更新后,以ON子句开头):

on     Onyx.iownerid = mscrm.fi_id.search 
AND    onyx.question = mscrm.question 
AND    (
   onyx.questiontype  NOT IN (1,2)
   OR (
      (onyx.questiontype=2 AND onyx.response = mscrm.answer)
      OR (onyx.questiontype=1 AND onyx.response=( 
                                          SELECT TOP 1 
                                                 vchparameterdesc 
                                          FROM   db..referenceparameters 
                                          WHERE  iparameterid=mscrm.answer
                                        ) 
          )
      )
   )

哦,顺便说一下,上面的代码假设没有列可以为NULL。如果他们可以,你也需要处理NULL的可能性。