MS SQL - 有一种快速的方法来引用case语句的结果而无需重新执行case语句吗?

时间:2012-01-18 15:54:04

标签: sql-server

......换句话说......

如果我有一个案例陈述,那就是......

Case
when Type = 'payment' then net *-1
else net
end as 'pos_neg'

如何在另一个通过>分割付款和收据的案例陈述中使用该结果?或者<那个0。

我想做的就是这个......

Case
when 'pos_neg' >0 then 'pos_neg'
else 0 end as 'Receipts'

....与付款相反。

我知道实现这一点的唯一方法是将第一个案例嵌套在第二个案例中....这是很多重复。

2 个答案:

答案 0 :(得分:0)

您可以从嵌套的select语句中进行选择。

select case when 'pos_neg' > 0 then 'pos_neg' else 0 end as 'Receipts'
from
  (Select case when Type = 'payment' then net*-1 else net end as 'pos_neg'
  From Table) T

或使用公用表表达式

with T(pos_neg) as (
  Select case when Type = 'payment' then net*-1 else net end as pos_neg
  From Table)
select case when pos_neg > 0 then pos_neg else 0 end as Receipts
from T

答案 1 :(得分:0)

select 
  case 
    when Type = 'payment' and net * -1 > 0
        then 'pos_neg'
    when Type = 'payment' and net * -1 <= 0
        then ...
    ...
    else 0 end as [Receipts]