cnd
cnd

Reputation: 33744

Optimize select query (inner select + group)

My current version is :

SELECT     DT, AVG(DP_H2O) AS Tx,
           (SELECT    AVG(Abs_P) / 1000000 AS expr1
           FROM       dbo.BACS_MinuteFlow_1
           WHERE      (DT =
                                     (SELECT     MAX(DT) AS Expr1
                                       FROM      dbo.BACS_MinuteFlow_1
                                       WHERE     DT <= dbo.BACS_KongPrima.DT ))
          GROUP BY DT) AS Px
  FROM    dbo.BACS_KongPrima
  GROUP BY DT

but it works very slow.

basically in inner select I'm selecting maximum near time to my time, then group by this nearest time.

Is there possible optimizations ? Maybe I can join it somehow , but the trouble I'm not sure how to group by this nearest date.

Thank you

Upvotes: 0

Views: 338

Answers (1)

Mark
Mark

Reputation: 1519

You could try to rearrange it to use the code below using a cross apply. Am not sure if this will improve performance but generally I try to avoid at all costs using a query on a specific column and SQL Server is pretty good at optimising the Apply statement.

WITH  Bacs_MinuteFlow_1  (Abs_P ,DT ) AS
(SELECT 5.3,'2011/10/10'
    UNION SELECT 6.2,'2011/10/10'
    UNION SELECT 7.8,'2011/10/10'
    UNION SELECT 5.0,'2011/03/10'
    UNION SELECT 4.3,'2011/03/10'),
BACS_KongPrima (DP_H2O ,DT)AS
(SELECT 2.3,'2011/10/15'
    UNION SELECT 2.6,'2011/10/15'
    UNION SELECT 10.2,'2011/03/15')

SELECT DT, AVG(DP_H2O) AS Tx,
       a.Px

FROM    BACS_KongPrima
CROSS APPLY  
(
SELECT AVG(Abs_P) / 1000000 AS Px 
FROM BACS_MinuteFlow_1 
WHERE DT =
    (SELECT     MAX(DT) AS maxdt 
     FROM      BACS_MinuteFlow_1
     WHERE     DT <= BACS_KongPrima.DT
    )
) a
GROUP BY DT,a.Px

Cheers

Upvotes: 1

Related Questions