我想在sql中获得数字x的正面部分。这意味着如果x> 0则结果为x,否则为零。我的意思是在聚合函数之后使用它。
select 1 as num, 200 as weight into #table
insert into #table values
(8, 100),
(10, 200),
(11, -300),
(20, -100);
直到现在我一直在使用以下内容:
select sum(num * weight)/sum(weight) as Result,
IIf(sum(num * weight)/sum(weight)>0, sum(num * weight)/sum(weight), 0) as PositivePartResult
from #table
但是,功能变得越来越不明确。是否有内置函数可以在不重复公式的情况下获得相同的结果?
答案 0 :(得分:4)
编写相同查询的另一种方法是:
select Result,
case when Result > 0 Then Result else 0 end as PositivePartResult
from
(
select sum(num * weight)/sum(weight) as Result
from #table
)T
答案 1 :(得分:0)
您可以计算内联值,或者,如果您经常这样做,请创建用户定义的函数:
create function PositiveValue( @N as Int )
returns Int as
begin
return ( Sign( @N ) + 1 ) / 2 * @N;
end;
go
declare @Samples as Table ( N Int );
insert into @Samples ( N ) values ( -42 ), ( -1 ), ( 0 ), ( 1 ), ( 42 );
select N, ( Sign( N ) + 1 ) / 2 * N as PositiveValue1, dbo.PositiveValue( N ) as PositiveValue2
from @Samples;
-- drop function dbo.PositiveValue;