我有一个处理数千行的SQL Server查询。但是脚本运行正常,但是我只需要在一个select语句中应用一个条件,但不会影响其余的结果。
Select
Count ([key]) as KEYCOUNT,
Round (AVG ([AGE]),2) as AGE,
Round (AVG ([LENGTH]),2) as Length_X,
Round (AVG ([Duration]),2) as DUR_Y,
from
[dbo].[XYZ]
where
[FLAG] = 1 and STAT = 3
我需要影响的选择是Round (AVG ([LENGTH]),2) as Length_X
,我需要将其计算为仅大于0的长度的平均值,基本上不包括所有0(零)
非常感谢
干杯
答案 0 :(得分:1)
您可以使用case
表达式作为AVG
函数的参数:
Round(AVG(case when [LENGTH] > 0 then [LENGTH] end), 2) as Length_X,
这样,AVG
将忽略所有0值,而查询中的所有其他表达式都不会受到影响。
答案 1 :(得分:0)
我需要计算的是只有那些大于0的长度的平均值,基本上不包括所有0(零)
如果需要,这是正和(长度)/总和(情况下长度为0然后0否则1结束)和适当的铸造。例如。
set nocount on;
with cte as (select * from (values (0), (1), (2), (1), (0), (0)) as l(length))
select avg(cast(length as float)) as avg1,
sum(cast(length as float)) / sum(case length when 0 then 0 else 1 end) as avg2
from cte;
with cte as (select * from (values (1), (2), (1) ) as l(length))
select avg(cast(length as float)) as avg1,
sum(cast(length as float)) / sum(case length when 0 then 0 else 1 end) as avg2
from cte;
注意案件情况。我用"不是零",你说"大于零"。你选。