我有以下SQL语句:
SELECT SomeData.., Order.EurAmount AS OrderTotalEeur,
--Begin Subselect
(SELECT Sum(Invoice.EurAmount)
FROM Invoice WHERE Invoice.OrderId = Order.Id
GROUP BY Invoice.OrderId) As InvoiceTotalEur
--End Subselect
([Order].EurAmount - IIF(InvoiceTotalEur is null, 0, InvoiceTotalEur) AS Diff
FROM [Order]
正如你所看到的,我希望获得2笔金额(OrderTotalEur和InvoiceTotalEur),没什么大不了的。但是我也想使用这两个别名来计算另一个不起作用的列(Diff),因为它不能识别用于计算diff列的两个别名。
我可以做的是重复Subselect两次(对于iif和值)但这不是正确的方法,对吗?
答案 0 :(得分:3)
您可以将查询视为子查询:
SELECT SomeData..,
OrderTotalEeur,
InvoiceTotalEur,
(OrderTotalEeur - IIF(InvoiceTotalEur is null, 0, InvoiceTotalEur) AS Diff
FROM (
SELECT SomeData.., Order.EurAmount AS OrderTotalEeur,
--Begin Subselect
(SELECT Sum(Invoice.EurAmount)
FROM Invoice WHERE Invoice.OrderId = Order.Id
GROUP BY Invoice.OrderId) As InvoiceTotalEur
--End Subselect
FROM [Order]
) myquery
然后在上一级你可以访问别名。