如何将别名列引用到SQL中临时表的另一列?

时间:2015-09-08 16:55:10

标签: sql sql-server tsql

我正在研究基于Excel工作表的算法,并试图在SQL中转换逻辑。在我的SQL逻辑中需要创建一个临时表,并且我在该表的另一个别名列中引用了一个别名列。它看起来像这样 -

INSERT INTO @tbl_CensusTable AS CST
SELECT CS.gender, CS.salary, CS.birthday, CS.Age,
    (some calculation) AS 'Column_5', (Some calculation * CST.Column_5) AS Column_6 
From @tbl_tempTable CS

我是否正确编写SQL语句?我能否按照上面例子中使用的方式在Column_6中引用Column_5?

3 个答案:

答案 0 :(得分:1)

试试这个:

INSERT INTO @tbl_CensusTable
SELECT CS.gender, 
    CS.salary, 
    CS.birthday, 
    CS.Age,
    (Col5 calculation) AS 'Column_5', 
    ((Some calculation) * (Col5 calculation)) AS Column_6 
From @tbl_tempTable as CS

这也应该有效:

WITH CTE as (
    SELECT CS.gender, 
        CS.salary, 
        CS.birthday, 
        CS.Age,
        (Col5 calculation) AS 'Column_5'
    From @tbl_tempTable as CS
)

INSERT INTO @tbl_CensusTable
    SELECT CS.gender, 
        CS.salary, 
        CS.birthday, 
        CS.Age,
        Column_5, 
        ((SomeCalculation) * Column_5) AS Column_6 
    From CTE as CS

答案 1 :(得分:0)

INSERT INTO @tbl_CensusTable (<good practice to list the columns here>)
SELECT
    CS.gender, CS.salary, CS.birthday, CS.Age,
    CS.Column_5,
    <another calculation> * CS.Column_5 AS Column_6
FROM
    (SELECT *, <some calculation> AS Column_5 FROM @tbl_tempTable) AS CS

;WITH CS AS (
    SELECT *, <some calculation> AS Column_5 
    FROM @tbl_tempTable
)
INSERT INTO @tbl_CensusTable (<good practice to list the columns here>)
SELECT
    CS.gender, CS.salary, CS.birthday, CS.Age, 
    CS.Column_5,
    <another calculation> * CS.Column_5 AS Column_6
FROM CS

答案 2 :(得分:0)

尝试滥用表值构造函数:

sessionStorage