创建一个将两列相加的值

时间:2018-03-05 18:19:21

标签: sql sql-server calculated-columns

我正在尝试定义名为End Year的新列,它是另一列的计算加上表示年数的数字。由于某些原因,我的脚本无法使用SQL Server 2008中SQL语句下面的摘录识别名为Allocation Year的新列。请注意,Contract Year是在非编辑完整脚本中标识的现有列:

,[Allocation Type] =
CASE 
WHEN left([contract type] ,1)'1' = THEN 'O&M'
ELSE 'N/A'
END
,[Allocation Year] =
CASE
WHEN [Contract Year]='XXXX' THEN '0'
ELSE CAST ([Contract Year] AS INT)
END
,[End Year] =
CASE
WHEN [Allocation Type]='O&M' THEN [Allocation Year] + 6
END

3 个答案:

答案 0 :(得分:0)

列以=关键字命名(在许多情况下也可以省略),而不是SELECT运算符。

SQL Server不允许您引用SELECT *, CASE WHEN [Allocation Type] = 'O&M' THEN [Allocation Year Temp] + 6 ELSE NULL END AS [Allocation Year] FROM ( SELECT CASE WHEN LEFT( [Contract type], 1 ) = '1' THEN 'O&M' ELSE 'N/A' END AS [Allocation Type], CASE WHEN [Contract Year] = 'XXXX' THEN '0' ELSE CAST( [Contract Year] AS int ) END AS [Allocation Year Temp], * FROM .... ) 子句中的其他列或别名 - 您必须使用子查询:

像这样:

from bs4 import BeautifulSoup

data = open(directory +'\\'+ file)
soup = BeautifulSoup(data, 'html.parser')

答案 1 :(得分:0)

如果要将所有内容放在一个选择查询中,请尝试使用此查询。希望这可以帮助。感谢。

,[End Year] =
CASE
WHEN left([contract type] ,1)='1' THEN 
  (CASE
    WHEN [Contract Year]='XXXX' THEN 6
   ELSE (CAST ([Contract Year] AS INT) + 6 )
  END)
END

答案 2 :(得分:0)

您无法在SELECT语句中引用计算列。您将不得不重复计算(或使用像Dai建议的子查询):

,[Allocation Type] =
CASE 
WHEN left([contract type] ,1)='1' THEN 'O&M'
ELSE 'N/A'
END
,[Allocation Year] =
CASE
WHEN [Contract Year]='XXXX' THEN 0
ELSE CAST ([Contract Year] AS INT)
END
,[End Year] =
CASE
WHEN left([contract type] ,1)='1' THEN (CASE
                                        WHEN [Contract Year]='XXXX' THEN 0
                                        ELSE CAST ([Contract Year] AS INT)
                                        END) + 6
END