从列表中选择或选择SQL中的所有值

时间:2020-07-23 16:06:31

标签: sql sql-server where-clause sql-in

SQL Server问题- 我正在尝试从一个名为BUDGET的表中获取一些记录。使用的过滤器是成本中心(CostC)。 我创建了查询,以便如果有多个CostC,那么它将是

select costc,description,budget from BUDGET where costc IN ('c1',c2',c3')

但是我还需要一个功能,以便在没有列表的情况下,COSTC上的筛选器应查找所有(*)成本中心。

2 个答案:

答案 0 :(得分:0)

一个选项使用union allnot exists

select costc, description, budget 
from budget 
where costc in ('c1', 'c2', 'c3')
union all
select costc, description, budget 
from budget
where not exists (select 1 from budget where costsc in ('c1', 'c2', 'c3'))

您还可以使用窗口功能:

select costc, description, budget 
from (
    select 
        b.*, 
        max(case when costc in ('c1', 'c2', 'c3') then 1 else 0 end) over() has_match
    from budget b
) b
where costc in ('c1', 'c2', 'c3') or has_match = 0

答案 1 :(得分:0)

您可以从@GMB的答案中重写联合:

select costc, description, budget 
from budget 
where costc in ('c1', 'c2', 'c3')
or not exists (select 1 from budget where costc in ('c1', 'c2', 'c3'))

最终的执行计划可能与工会的执行计划相同。

还是便宜地生成所有costc的列表:

select something
from manymanyjoinsquery 
where costc in 
(  select costc 
        from budget 
        where costc in ('c1', 'c2', 'c3')
        or not exists (select 1 from budget where costsc in ('c1', 'c2', 'c3'))
)
相关问题