简体   繁体   中英

Better way to write this sql - CTE/Temp table

I could really do with some help on how to write this code in a more effective way. I am basically creating a CTE to hold a data set containing vehicles, by day and the weight of containers they load. The containers need to be a certain weight hence the pass/fail fields.

All I am trying to do is take the lift level detail in the CTE and aggregate it to have number of lifted containers that pass/fail the criteria and aggregate the reasons for any failed lifts.

I am just wondering if the best way is to use a CTE or whether temp table or any of method would speed it up or be more standard practice?

Ideally I'd post an image of the CTE data and then the output data but I can't post an image:(

Many thanks in advance

WITH DetailLifts
     AS (SELECT CO.Description                      'Outlet',
                LE.[VehicleCode],
                S.FORENAME + ' ' + S.SURNAME        AS Name,
                le.[CollectionDate],
                le.lifteventid,
                C.CustomerName,
                Cast([CollectionTimeStamp] AS TIME) 'CollectionTime',
                LE.[NetWeight],
                le.grossweight,
                le.tareweight,
                ct.description,
                CASE
                  WHEN CT.Description LIKE 'Euro%' THEN 10
                  WHEN CT.Description LIKE 'FEL%' THEN 30
                END                                 'Threshold',
                CASE
                  WHEN le.Grossweight IS NOT NULL
                       AND le.grossweight - le.tareweight < ( CASE
                                                                WHEN CT.Description LIKE 'Euro%' THEN -10
                                                                WHEN CT.Description LIKE 'FEL%' THEN -30
                                                              END )
                        OR le.grossweight - le.tareweight > ( CASE
                                                                WHEN CT.Description LIKE 'Euro%' THEN 10
                                                                WHEN CT.Description LIKE 'FEL%' THEN 30
                                                              END ) THEN 1
                  WHEN le.grossweight IS NULL
                       AND le.netweight < ( CASE
                                              WHEN CT.Description LIKE 'Euro%' THEN -10
                                              WHEN CT.Description LIKE 'FEL%' THEN -30
                                            END )
                        OR le.netweight > ( CASE
                                              WHEN CT.Description LIKE 'Euro%' THEN 10
                                              WHEN CT.Description LIKE 'FEL%' THEN 30
                                            END ) THEN 1
                  WHEN le.netweight IS NULL THEN 0
                  WHEN le.grossweight = 0
                       AND le.tareweight = 0
                       AND le.netweight = 0 THEN 0
                  ELSE 0
                END                                 'Overweight',
                CASE
                  WHEN Isnull([LiftText], 'No') = 'No' THEN 1
                  ELSE 0
                END                                 AS 'NoLift',
                CASE
                  WHEN Isnull([LiftText], 'No') = 'no' THEN 0
                  ELSE 1
                END                                 AS 'Lifts',
                CASE
                  WHEN SOI.SiteOrderId IS NULL THEN 'Not Matched'
                  ELSE 'Matched'
                END                                 AS 'MatchedLogic',
                CASE
                  WHEN Isnull([LiftText], 'No') = 'No'
                       AND LiftInformationId IS NOT NULL THEN 'Yes'
                  ELSE 'No'
                END                                 'Reason Code Used',
                r2.Description                      AS 'ReasonCode',
                CASE
                  WHEN le.Grossweight IS NOT NULL
                       AND le.grossweight - le.tareweight < ( CASE
                                                                WHEN CT.Description LIKE 'Euro%' THEN -10
                                                                WHEN CT.Description LIKE 'FEL%' THEN -30
                                                              END )
                        OR le.grossweight - le.tareweight > ( CASE
                                                                WHEN CT.Description LIKE 'Euro%' THEN 10
                                                                WHEN CT.Description LIKE 'FEL%' THEN 30
                                                              END ) THEN 0
                  WHEN le.grossweight IS NULL
                       AND le.netweight < ( CASE
                                              WHEN CT.Description LIKE 'Euro%' THEN -10
                                              WHEN CT.Description LIKE 'FEL%' THEN -30
                                            END )
                        OR le.netweight > ( CASE
                                              WHEN CT.Description LIKE 'Euro%' THEN 10
                                              WHEN CT.Description LIKE 'FEL%' THEN 30
                                            END ) THEN 0
                  WHEN ( Substring(le.vehiclecode, 3, 2) IN ( 57, 58, 63, 14,
                                                              64, 15, 65 )
                          OR ct.description LIKE '%fel%' )
                       AND le.netweight IS NOT NULL
                       AND le.grossweight IS NULL THEN 0
                  WHEN le.netweight IS NULL
                        OR ( le.grossweight = 0
                             AND le.tareweight = 0 ) THEN 0
                  ELSE 1
                END                                 'Pass',
                CASE
                  WHEN le.Grossweight IS NOT NULL
                       AND le.grossweight - le.tareweight < ( CASE
                                                                WHEN CT.Description LIKE 'Euro%' THEN -10
                                                                WHEN CT.Description LIKE 'FEL%' THEN -30
                                                              END )
                        OR le.grossweight - le.tareweight > ( CASE
                                                                WHEN CT.Description LIKE 'Euro%' THEN 10
                                                                WHEN CT.Description LIKE 'FEL%' THEN 30
                                                              END ) THEN 1
                  WHEN le.grossweight IS NULL
                       AND le.netweight < ( CASE
                                              WHEN CT.Description LIKE 'Euro%' THEN -10
                                              WHEN CT.Description LIKE 'FEL%' THEN -30
                                            END )
                        OR le.netweight > ( CASE
                                              WHEN CT.Description LIKE 'Euro%' THEN 10
                                              WHEN CT.Description LIKE 'FEL%' THEN 30
                                            END ) THEN 1
                  WHEN ( Substring(le.vehiclecode, 3, 2) IN ( 57, 58, 63, 14,
                                                              64, 15, 65 )
                          OR ct.description LIKE '%fel%' )
                       AND le.netweight IS NOT NULL
                       AND le.grossweight IS NULL THEN 1
                  WHEN le.netweight IS NULL
                        OR ( le.grossweight = 0
                             AND le.tareweight = 0 ) THEN 1
                  ELSE 0
                END                                 'Fail',
                lifttext,
                CASE
                  WHEN ( Substring(le.vehiclecode, 3, 2) IN ( 57, 58, 63, 14,
                                                              64, 15, 65 )
                          OR ct.description LIKE '%fel%' )
                       AND le.netweight IS NOT NULL
                       AND le.grossweight IS NULL THEN 1
                  ELSE 0
                END                                 AS 'VehicleFault'
         FROM   [CFO_P155_Pre_Production_ELEMOS].[dbo].[LiftEvent]LE
                LEFT JOIN CFO_P155_Pre_Production_ELEMOS.dbo.Route RT
                       ON RT.routeid = le.routeid
                LEFT JOIN CFO_P155_Pre_Production_ELEMOS.dbo.SysUser S
                       ON S.sysuserid = RT.driversysuserid
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[Vehicle]V
                       ON LE.VehicleId = V.VehicleId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[CompanyOutlet]CO
                       ON V.CompanyOutletId = CO.CompanyOutletId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[Reason]R
                       ON LE.LiftProblemId = R.ReasonId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[Reason]R2
                       ON LE.LiftInformationId = R2.ReasonId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[SiteOrderItem]SOI
                       ON SOI.SiteOrderItemId = LE.SiteOrderItemId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[SiteOrder]SO
                       ON SOI.SiteOrderId = SO.SiteOrderId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[CustomerSite]CS
                       ON SO.CustomerSiteId = CS.CustomerSiteId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[Location]L
                       ON CS.LocationId = L.LocationId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[Customer]C
                       ON CS.CustomerId = C.CustomerId
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[Material]M
                       ON SO.MaterialId = M.Materialid
                LEFT JOIN [CFO_P155_Pre_Production_ELEMOS].[dbo].[ContainerType]CT
                       ON SOI.ContainerTypeId = CT.ContainerTypeId
         WHERE  CO.Description IN ( 'Portsmouth' )
                AND le.CollectionDate >= '2015-03-02'
                AND le.CollectionDate <= '2015-03-06'
                AND ( ct.description LIKE '%euro%'
                       OR ct.description LIKE '%FEl%' )
                --and substring(le.vehiclecode,3,2) in (57,58,63,64,65) and le.netweight is         not null and le.grossweight is null
                AND C.Customerid = 18407)
SELECT dl.outlet,
       dl.collectiondate,
       dl.vehiclecode,
       dl.name,
       CASE
         WHEN passesandfails.Pass >= 5
              AND passesandfails.Fail = 0 THEN 'Pass'
         ELSE 'Fail'
       END                                        AS 'Pass or Fail',
       passesandfails.pass,
       passesandfails.fail,
       Isnull(matchedlifts.matchedActuallifts, 0) AS MatchedActualLifts,
       Isnull(lifted.NoLift, 0)                   AS 'MatchedNotLifted(Lift  Complete)',
       Isnull(overweights.overweight, 0)          AS Overweights,
       Sum(vehiclefault)                          AS VehicleFault
FROM   DetailLifts DL
       LEFT JOIN (SELECT outlet,
                         collectiondate,
                         vehiclecode,
                         Sum(pass) pass,
                         Sum(fail) fail
                  FROM   detaillifts dl
                  GROUP  BY outlet,
                            collectiondate,
                            vehiclecode) AS PassesandFails
              ON dl.Collectiondate = passesandfails.collectiondate
                 AND dl.vehiclecode = passesandfails.vehiclecode
       LEFT JOIN (SELECT outlet,
                         collectiondate,
                         vehiclecode,
                         Sum(overweight)AS overweight
                  FROM   detaillifts DL
                  GROUP  BY outlet,
                            collectiondate,
                            vehiclecode) AS Overweights
              ON dl.collectiondate = overweights.collectiondate
                 AND dl.vehiclecode = overweights.vehiclecode
       LEFT JOIN (SELECT collectiondate,
                         vehiclecode,
                         Count(lifteventid) AS MatchedActualLifts
                  FROM   detaillifts DL
                  WHERE  lifttext IS NOT NULL
                  GROUP  BY collectiondate,
                            vehiclecode) AS MatchedLifts
              ON dl.collectiondate = matchedlifts.collectiondate
                 AND dl.vehiclecode = matchedlifts.vehiclecode
       LEFT JOIN (SELECT collectiondate,
                         vehiclecode,
                         Sum(lifts)  AS Lifts,
                         Sum(nolift) AS NoLift
                  FROM   detaillifts
                  GROUP  BY collectiondate,
                            vehiclecode)AS lifted
              ON lifted.collectiondate = dl.collectiondate
                 AND lifted.vehiclecode = dl.vehiclecode
GROUP  BY dl.outlet,
          dl.collectiondate,
          dl.vehiclecode,
          dl.name,
          matchedActuallifts,
          passesandfails.pass,
          passesandfails.fail,
          lifted.nolift,
          overweights.overweight
ORDER  BY outlet,
          collectiondate,
          vehiclecode 

A CTE is just syntax and is evaluated
But if the CTE runs fast then not a problem
There is a cost to materialized to t #temp
How long does it take to run the CTE alone?
Hoe long does the whole query take?

But you have two joins you don't need

move Sum(overweight)AS overweight up into PassesandFails

move Count(lifteventid) down into to lifted as Count(lifttext)
null are not counted

That will cut the join overhead in 1/2

If you are getting the answer you expect then I don't see a purpose in posting data

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