如果第一个选择返回0计数,则返回备用视图结果

时间:2017-03-16 16:44:16

标签: sql sql-server view

我在SQL Server视图中有相当长的SQL选择。

但是,我想要一个条件,所以如果没有返回任何行,那么它会改变where子句。

查询概述如下:

SELECT COL1, COL2, COL3, COL4............(15 columns)
FROM TABLE1 inner join TABLE2 ON t1 = t2 (10 tables)
WHERE a = b

所以我想要的是,如果上面的查询返回0行,则返回结果:

SELECT COL1, COL2, COL3, COL4............(15 columns)
FROM TABLE1 inner join TABLE2 ON t1 = t2 (10 tables)
WHERE a = c

我如何在视图中解决这个问题?

提前致谢

2 个答案:

答案 0 :(得分:1)

使用a = b选择两个集合并优先使用a = c的{​​{1}}优先级:

RANK

如果某些记录确实存在SELECT COL1, COL2, COL3, COL4............(15 columns) FROM ( SELECT RANK() OVER (ORDER BY CASE WHEN a = b THEN 1 ELSE 2 END) AS rnk, COL1, COL2, COL3, COL4............(15 columns) FROM TABLE1 inner join TABLE2 ON t1 = t2 (10 tables) WHERE a IN (b, c)) AS t WHERE t.rnk = 1 ,则查询将准确选择这些记录,否则将返回a = b的记录。

答案 1 :(得分:1)

使用common table expression not exists()

;with cte as (
  /* big query here without where clause of `a = b` or `a = c` */
)
select * 
from cte
where a = b
  or ( a = c
    and not exists (select 1 from cte where a = b)
      )

示例:

create table t (value int);
insert t values (0),(1),(3),(4),(5);
with cte as (
  select *
  from t
)
select * 
from cte
where value = 2
  or ( value = 3 
    and not exists (select 1 from cte where value=2)
      )

返回3

rextester演示:http://rextester.com/NDC30620