Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to optimize query that has the same subquery twice?

Tags:

sql

sql-server

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?

like image 372
Daniel Martinez Avatar asked Sep 20 '13 15:09

Daniel Martinez


2 Answers

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!!

like image 182
Rahul Tripathi Avatar answered Nov 15 '22 21:11

Rahul Tripathi


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
like image 44
Luc M Avatar answered Nov 15 '22 21:11

Luc M