避免使用 OVER 子句除以零

Avoid divide by zero with the OVER clause

我有看法:

create view AA(
    select 
    ba.[FYear],right(ba.[FPeriodId],2) Month,am.[L1],am.L2,ba.[SS],ba.[SM],

    sum(ba.[TSB]) OVER (PARTITION BY right(ba.[FPeriodId],2),ba.[SS]) as 'X',
    ba.[TSB]/sum(ba.[TSB]) OVER (PARTITION BY right(ba.[FPeriodId],2),ba.[SS]) as 'Y'

    from [table1] ba left join [b1_map] am on ba.[SS1] = am.[SS1])

我想避免被零除,所以我使用 ISNULL:isnull(ba.[TSB]/sum(ba.[TSB]))

现在当我 运行 查询时:select * from AA 我收到消息:

"The function 'ISNULL' is not a valid windowing function, and cannot be used with the OVER clause."

我该如何解决这个问题?

使用NULLIF()避免被零除:

(ba.[TSB] /
 NULLIF(sum(ba.[TSB]) OVER (PARTITION BY right(ba.[FPeriodId],2), ba.[SS]), 0)
) as Y

此外,我不鼓励您对列别名使用单引号。有一天,当您 引用 列时,您将使用它们,引入一个难以调试的错误。仅对字符串和日期常量使用单引号。