0

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

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)

“ [US Pretax Income]+[FN Pretax Income] AS [Total Pretax Income] ”给了我错误:

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'.
4

3 回答 3

2

如果您将 case 语句放在 a中,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
于 2012-05-17T17:23:57.573 回答
2

您不能SELECT在同一SELECT. 为此使用 CTE 或派生表:

SELECT A.*, [US Pretax Income]+[FN Pretax Income] AS [Total Pretax Income] 
FROM (
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]
FROM AccessEntityList
INNER JOIN TestTabI 
ON AccessEntityList.[Entity Number] = TestTabI.[Entity Number]
WHERE (((TestTabI.Month)=12) AND ((TestTabI.Year)=2010)) A
于 2012-05-17T17:25:15.493 回答
0

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

对于您的别名,请尝试用反引号替换括号,以便:

end AS `US Pretax Income`, 
于 2012-05-17T17:17:44.363 回答