使用 SELECT 列表中的表达式来精简 CASE 语句

Kai*_*Kai 2 sql-server sql-server-2008-r2 select case

我有一个查询,我通过重写工作-它有一个巨大的一堆case文中陈述select列表中的所有基本是这样的:

select
    Column1 = 
        case when (Something = 2) and (SomethingElse is null) and (AnotherThing in (1, 2))
        then 1 
        else 0
        end,
    Column2 = 
        case when (Something = 3) and (SomethingElse is not null) and (AnotherThing in (2, 3))
        then 1 
        else 0
        end,
    ...
Run Code Online (Sandbox Code Playgroud)

特别注意when <expressions> then 1 else 0所有这些通用的“ ”逻辑。

它看起来真的很臃肿和冗长,是对case语句的粗暴使用- 我的编程大脑告诉我这可以通过一些基本的二进制&逻辑更简洁地实现,case完全删除:

select
    Column1 = (Something = 2) & (SomethingElse is null) & (AnotherThing in (1, 2)),
    Column2 = (Something = 3) & (SomethingElse is not null) & (AnotherThing in (2, 3)),
    ...
Run Code Online (Sandbox Code Playgroud)

不幸的是,虽然 SQL Server 能够处理类似select 1 & 0(returns 0) 之类的事情,但它似乎在解析选择列表 ( Incorrect syntax near '=')中的表达式时卡住了- 是否可以执行此类操作?也许是某种评估函数?

Rob*_*ley 5

T-SQL 不支持这样的布尔值。但是您可以将 CROSS APPLY 与使用 CASE 生成一堆 1 和 0 的子查询一起使用,然后使用按位运算符 & 和 | 将它们组合在 SELECT 子句中。