两个选择语句与案例

时间:2016-12-05 04:29:03

标签: sql sql-server-2008

我有两个查询,如果值为1,则我有一个值,如果值为2则接第一个查询将执行。我怎样才能实现这一点,我的查询是

如果值为1,则查询一个

SELECT  count (CASE WHEN col1 = 9 THEN 1 ELSE 0 END  )AS "matches" ,
              CAST( CASE WHEN col1 = 9 THEN 1 ELSE 0 END  AS VARCHAR(10)) + ' / 1' AS "match by"
              FrOM table a
              where ( SELECT  CASE WHEN col1 = 9 THEN 1 ELSE 0 END  AS "matches"  )  >= 1
              group by  ( CASE WHEN col1 = 9 THEN 1 ELSE 0 END ) 
              )

如果值2

,则查询2
 SELECT  count (CASE WHEN col1 = 9 THEN 1 ELSE 0 END    +  
                CASE WHEN col2 = 10 THEN 1 ELSE 0 END  
                )AS "matches" ,
                CAST( CASE WHEN col1 = 9 THEN 1 ELSE 0 END 
                +  CASE WHEN col2 = 10 THEN 1 ELSE 0 END AS VARCHAR(10)) + '/ 2'  AS "match by"
                FrOM table a
                where ( SELECT  CASE WHEN col1 = 9 THEN 1 ELSE 0 END + 
                 CASE WHEN col2 = 10 THEN 1 ELSE 0 END AS "NUM_OF_MATCHES"  )  >= 1
                group by  ( CASE WHEN col1 = 9 THEN 1 ELSE 0 END+ 
                 CASE WHEN col2 = 10 THEN 1 ELSE 0 END ) 

我已尝试使用案例,但它无效

我想if value = 1然后第一个查询将运行,if value = 2然后第二个

虽然两个查询都做同样的工作,但是如果值为1则col1逻辑只接受col1,如果value为2则接受col1和col2,如果value为3则接受col1 col2和col3直到6 col

1 个答案:

答案 0 :(得分:-1)

你还在使用CASE Statement,为什么不尝试使用IIF Statement,IIF Statement比CASE Statement更有效率和快速。

e.g。

select IIF(1=1, (your desired column1),(your desired column2)) as matches

您还可以在CASE语句等单一查询中使用嵌套的IIF语句。

select IIF(1=1, (IIF(2=2, (your desired column1),(your desired column2))),(your desired column3)) as matches.