I'm trying to improve some queries performance, the queries' structure is something as follows:
select 'Total_amount',
(select SUM(Total) from dbo.Invoices i where i.BU = bun.BU),
case when (select SUM(Total) from dbo.Invoices i where i.BU = bun.BU) > 100000 then 'Good' else 'Not good' end
from dbo.BusinessUnits bun
I know this example can be solved using joins, but on my real queries I need the subqueries. As you may notice, I have the same subquery twice, one to give the actual value and another one to calculate a status.
Is there a way to improve performance by just calculating the subquery once?
You may try using OUTER APPLY like this:-
select 'Total_amount', SumTotal, case when SumTotal > 100000
then 'Good' else 'Not good' end
from dbo.BusinessUnits bun
OUTER APPLY (select SUM(Total)
from dbo.Invoices i where i.BU = bun.BU) CA(SumTotal)
SPECIAL THANKS TO MARTIN SMITH for pointing that!!
Another option using WITH
WITH total_table( 'Total_amount' )
AS
( SELECT SUM(Total)
FROM Invoices INNER JOIN BusinessUnits ON (Invoices.BU = BusinessUnits.BU )
)
SELECT
CASE WHEN Total_amount > 100000 then 'Good'
ELSE 'Not good'
END
FROM
total_table
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With