在sql查询中减去两列

时间:2016-05-04 12:46:18

标签: sql-server

我一直在尝试在sql server中减去两列以形成第三列。以下是我的查询

select  AD.Id, Sum(APS.Amount) AS TotalDue,
isnull((select sum(Amount) from Activation where InvoiceId in (select InvoiceId from Invoices where AgreementId = AD.Id)),0)
As AllocatedToDate 
from AdvantageDetails AD 
inner join AllPaymentsSubstantial APS
on APS.AgreementId=AD.Id
where AD.OrganizationId=30
group by AD.Id

我尝试过的是下面但它无法正常工作。 :

select  AD.Id, Sum(APS.Amount) AS TotalDue,
isnull((select sum(Amount) from Activation where InvoiceId in (select InvoiceId from Invoices where AgreementId = AD.Id)),0)
As AllocatedToDate , (TotalDue-AllocatedToDate) as NewColumn
from AdvantageDetails AD 
inner join AllPaymentsSubstantial APS
on APS.AgreementId=AD.Id
where AD.OrganizationId=30
group by AD.Id

最后我尝试使用CTE工作正常。但我想在不创建CTE的情况下这样做。可以有任何其他方式来执行相同的功能。我不想使用CTE,因为它在那里被预测 可以是将来计算的其他列。

with CTE as(select  AD.Id, Sum(APS.Amount) AS TotalDue,
isnull((select sum(Amount) from Activation where InvoiceId in (select InvoiceId from Invoices where AgreementId = AD.Id)),0)
As AllocatedToDate , (TotalDue-AllocatedToDate) as NewColumn
from AdvantageDetails AD 
inner join AllPaymentsSubstantial APS
on APS.AgreementId=AD.Id
where AD.OrganizationId=30
group by AD.Id) select * , (CTE.TotalDue-CTE.AllocatedToDate)As Newcolumn from CTE

2 个答案:

答案 0 :(得分:3)

通过重复构成AllocatedToDate的整个公式,您可以在没有CTE的情况下完成。

您不能在SELECT列表中使用列的别名,因此您无法执行此操作:

SELECT {some calculation} AS ColumnA, (ColumnA - ColumnB) AS ColumnC

如果您不想使用CTE或派生表,则必须这样做:

SELECT {some calculation} AS ColumnA, ({some calculation} - ColumnB) AS ColumnC

顺便说一句,我无法想象为什么未来列的可能性是不使用CTE的原因。对我来说,这听起来像是使用CTE的原因,因为您只需要在代码中的一个位置进行更改,而不是在同一查询中的不同位置复制相同的代码。

答案 1 :(得分:-1)

您可以使用嵌套查询:

select Id, TotalDue, AllocatedToDate, (TotalDue-AllocatedToDate) as NewColumn
from (
    select  AD.Id, Sum(APS.Amount) AS TotalDue,
        isnull((select sum(Amount) from Activation where InvoiceId in (select InvoiceId from Invoices where AgreementId = AD.Id)),0)
        As AllocatedToDate 
    from AdvantageDetails AD 
    inner join AllPaymentsSubstantial APS
        on APS.AgreementId=AD.Id
    where AD.OrganizationId=30
    group by AD.Id
) x