尝试在查询中使用列别名时获取“无效列”

时间:2012-05-17 17:12:45

标签: sql-server

我正在尝试使用我在查询中创建的列别名,在同一查询中的公式内使用不同的列。我在这里做错了什么,我该如何解决?这里是更好地解释自己的代码:

SELECT TestTabI.Month, TestTabI.Year, AccessEntityList.Region, 
AccessEntityList.[Audit Tier], AccessEntityList.[Parent Group],
case 
when AccessEntityList.[Jurisdiction]='U.S.' 
then [NF PTI] 
else 0 
end AS [US Pretax Income], 

case 
when AccessEntityList.[Jurisdiction]='Non-U.S.' 
then [NF PTI] 
else 0 
end AS [FN Pretax Income],

[US Pretax Income]+[FN Pretax Income] AS [Total Pretax Income] FROM AccessEntityList
INNER JOIN TestTabI ON AccessEntityList.[Entity Number] = 
TestTabI.[Entity Number] WHERE (((TestTabI.Month)=12) AND ((TestTabI.Year)=2010)

“[美国税前收入] + [FN税前收入] AS [总税前收入]”给出了错误:

Msg 207, Level 16, State 1, Line 7
Invalid column name 'US Pretax Income'.
Msg 207, Level 16, State 1, Line 7
Invalid column name 'FN Pretax Income'.

3 个答案:

答案 0 :(得分:2)

您无法在同一SELECT的{​​{1}}上使用您刚刚定义的别名。为此使用CTE或派生表:

SELECT

答案 1 :(得分:1)

如果您将案例陈述放在cross apply中,则可以使用别名。

select TestTabI.Month,
       TestTabI.Year,
       AccessEntityList.Region, 
       AccessEntityList.[Audit Tier], 
       AccessEntityList.[Parent Group],
       C.[US Pretax Income], 
       C.[FN Pretax Income],
       C.[US Pretax Income]+C.[FN Pretax Income] AS [Total Pretax Income] 
from AccessEntityList
  inner join TestTabI 
    on AccessEntityList.[Entity Number] = TestTabI.[Entity Number] 
  cross apply
    (
     select case 
              when AccessEntityList.[Jurisdiction]='U.S.' 
              then [NF PTI] 
              else 0 
            end as [US Pretax Income], 
            case 
              when AccessEntityList.[Jurisdiction]='Non-U.S.' 
              then [NF PTI] 
              else 0 
            end as [FN Pretax Income]
    ) as C
where TestTabI.Month=12 and TestTabI.Year=2010

答案 2 :(得分:0)

我通常在列名中不使用空格,因此我不熟悉这种括号语法。你确定它适用于别名声明吗?

对于你的别名,尝试用反引号替换括号,所以:

end AS `US Pretax Income`,