使用isnull()函数和子查询

时间:2018-01-31 06:40:08

标签: sql-server

我有2个单独的列,' ATFTE'和' SATFTE'。使用这两列,我必须执行除法并将结果存储在单独的列中(比如金字塔)。我正在尝试使用isnull函数,因为在许多情况下,分母为0并将其带入子查询中。它显示错误 - '无效的列名称' - ATFTE和SATFTE。我怎样才能纠正它?

select isnull(ATFTE/SATFTE,0) as Pyramid
from dw_UtilizationPredictionReport
where WFMGrade in (
select WFMGrade,
    case 
        when WFMGrade IN ('P/PA','PAT','A') then sum(TotalFTE)
        else 0
    END as ATFTE,
    case
        when WFMGrade IN ('SA','M','SM','AD','D','SD','AVP','VP','SVP','EVP') 
        and WFMGrade NOT IN ('Cont') then sum(TotalFTE)
        else 0
    END as SATFTE
from dw_UtilizationPredictionReport
group by (WFMGrade)
)

3 个答案:

答案 0 :(得分:0)

试试这个:

select  CASE WHEN ISNULL(SATFTE,0) = 0 THEN 0
    ELSE ISNULL(ATFTE/SATFTE,0) 
    END AS Pyramid FROM
(select WFMGrade,
    case 
        when WFMGrade IN ('P/PA','PAT','A') then sum(TotalFTE)
        else 0
    END as ATFTE,
    case
        when WFMGrade IN ('SA','M','SM','AD','D','SD','AVP','VP','SVP','EVP') 
        and WFMGrade NOT IN ('Cont') then sum(TotalFTE)
        else 0
    END as SATFTE
from dw_UtilizationPredictionReport
group by (WFMGrade)) as tbl

在您的查询中,您似乎已经犯了以下错误:

  1. 您不能在WHERE中使用带有多个列的IN语句 子句。
  2. ATFTE / SATFTE不是表格的列 “dw_UtilizationPredictionReport”,所以你不能在它中使用它 选择。

答案 1 :(得分:0)

select a.WFMGrade, sum(b.TotalFTE) / sum(c.(TotalFTE)
from dw_UtilizationPredictionReport a
left join dw_UtilizationPredictionReport b 
on b.WFMGrade = a.WFMGrade 
and b.WFMGrade IN ('P/PA','PAT','A')
left join dw_UtilizationPredictionReport c 
on c.WFMGrade = a.WFMGrade 
and c.WFMGrade IN ('SA','M','SM','AD','D','SD','AVP','VP','SVP','EVP') 
group by a.WFMGrade

如果这对您有效,请尝试不必包含条件"续"因为你有条件。

答案 2 :(得分:0)

尝试第一位

SELECT 
    CASE 
        WHEN ISNULL(SATFTE,0) = 0 THEN 0 -- Or whatever you want
        ELSE ISNULL(ATFTE/SATFTE,0) 
    END AS Pyramid