别名

时间:2017-08-09 00:32:21

标签: sql sql-server

我有一个包含SUM方程的多个别名的查询。

现在我需要在更大的等式中使用这些别名,但显然不能在同一查询中使用别名。在一种情况下,我需要将总共约7个别名相加在一起,减去两个总和在一起的别名。有一个简单的方法吗?使用SQL Server

例如 -

ISNULL((SELECT  SUM(Addendums)
        FROM    v_Addendums
        WHERE   Job_ID = JM.Job_ID
                AND (JC.FundingType_ID <> 1 OR JC.FundingType_ID IS NULL)
                AND jobPhase_CompletedDate <= @dt1
                AND (Addendum_Date between @dt1-31 and @dt1)),0) AS Earn30,

ISNULL((SELECT  SUM(JM1.Draw_Amount) 
        FROM DrawSchedule AS JM1 INNER JOIN
             JobContracts AS JC1 ON JM1.Job_ID = JC1.Job_ID LEFT OUTER JOIN
             v_JobPhase ON JC1.Job_ID = v_JobPhase.Job_ID AND 
             JM1.JobPhase_ID = v_JobPhase.PhaseType_ID
        WHERE   (v_JobPhase.Completed IS NOT NULL)
            AND (JC.FundingType_ID <> 1 OR JC.FundingType_ID IS NULL)
            AND (v_JobPhase.Completed BETWEEN @dt1 - 61 AND @dt1-31) 
            AND (JM1.Job_ID = JM.Job_ID)),0) +
ISNULL((SELECT  SUM(Addendums)
        FROM    v_Addendums
        WHERE   Job_ID = JM.Job_ID
            AND (JC.FundingType_ID <> 1 OR JC.FundingType_ID IS NULL)
            AND jobPhase_CompletedDate <= @dt1
            AND (Addendum_Date between @dt1-61 and @dt1-31)),0) AS Earn60

说我需要添加Earn30 + Earn60 ..然后减去另一个类似的别名。

1 个答案:

答案 0 :(得分:0)

您可以使用SQL Server的CTE表(通用表表达式)来执行此操作。 e.g。

;with mycte as (
select 1 as line1 -- this is your statement with whatever and assigning it an alias
)

select
 line1 -- this is your alias column from the previous mycte
 , line1+1 as line2 -- just an example of playing with the alias
 from mycte