简体   繁体   中英

How to optimize query that has the same subquery twice?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM