如何引用前两列的结果,如Excel公式

时间:2015-08-05 05:12:28

标签: sql tsql

SELECT   
Answer_Code AS C0,   
Text AS C1,  
Price AS C2,   
sum(case when Response like '%PAID%' then 1 else 0 end) AS C3,
C2 * C3 AS 'Total'    --Invalid column name 'C2'.--
FROM TableA

如何引用C2和C3,然后在该位置进行乘法运算?

任何技巧?

2 个答案:

答案 0 :(得分:2)

您可以使用内部选择:

SELECT *, C2 * C3 As Total
FROM (
    SELECT   
        Answer_Code AS C0,   
        Text AS C1,  
        Price AS C2,   
        sum(case when Response like '%PAID%' then 1 else 0 end) AS C3,
    FROM TableA) DT;

或使用这样的CTE:

;WITH t AS (
    SELECT   
        Answer_Code AS C0,   
        Text AS C1,  
        Price AS C2,   
        sum(case when Response like '%PAID%' then 1 else 0 end) AS C3,
    FROM TableA)
SELECT *, C2 * C3 As Total
FROM t;

答案 1 :(得分:2)

您可以使用with子句或sub query

;with tmp_tbl as (
    SELECT   
    Answer_Code AS C0,   
    Text AS C1,  
    Price AS C2,   
    sum(case when Response like '%PAID%' then 1 else 0 end) AS C3
    --C2 * C3 AS 'Total'    --Invalid column name 'C2'.--
    FROM TableA
)
select
    C0,
    C1,
    C2,
    C3,
    C2 * C3 AS 'Total'
from tmp_tbl;