希望下面的代码能说明我想要实现的目标。
问题在于,当我尝试计算VatableCash
时,没有任何输入选择被解析,因此在尝试选择时会出现“无效列”。
对不起,如果我能在这里做一些明显的事情。 SQL不是我的强项之一。
select
OrderHeader.ID,
sum(OrderLine.NetPrice) as OrderLineNetPrice,
sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
sum(
case when PaymentOption_ID = 8
then Payment.Amount
else 0
end
) as TotalCashAmount,
((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
from OrderHeader
inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
group by OrderHeader.ID
答案 0 :(得分:2)
您需要使用子查询。
你可以试试这个。
;WITH CTE AS
(
select
OrderHeader.ID,
sum(OrderLine.NetPrice) as OrderLineNetPrice,
sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
sum(
case when PaymentOption_ID = 8
then Payment.Amount
else 0
end
) as TotalCashAmount
from OrderHeader
inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
group by OrderHeader.ID
)
SELECT *,
((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
FROM CTE
答案 1 :(得分:2)
爱十字架申请!只要你想要一些方便的额外列,就可以使用它。
select
OrderHeader.ID,
sum(OrderLine.NetPrice) as OrderLineNetPrice,
sum(OrderLine.GrossPrice) as OrderLineGrossPrice,
TotalCashAmount,
((OrderLineGrossPrice - OrderLineNetPrice) / OrderLineGrossPrice) * TotalCashAmount as VatableCash
from OrderHeader
inner join Payment on Payment.OrderHeader_ID = OrderHeader.ID
inner join OrderLine on OrderLine.OrderHeader_ID = OrderHeader.ID
cross apply ( select sum(
case when PaymentOption_ID = 8
then Payment.Amount
else 0
end
)) as subquery(TotalCashAmount)
group by OrderHeader.ID