查询需要15分钟以上才能执行

时间:2019-12-09 19:03:43

标签: sql-server database query-optimization

我有一个类似下面的查询:

SELECT 
[User Country] AS  [Country Name],
Count( distinct [User EmpPK]) as [Unique participant] ,
CAST(SUM ( [Learning hours]) AS Decimal(11,2)) as [Total Learning Hours] 
FROM (Select d."User EmpPK" ,
         act."Activity PK" ,
         max(d.[Attempt Start Date]) "Attempt Start Date",
         max(d.[Attempt Completion Date]) "Attempt Completion Date",
         act."Region" ,
         act."Activity Code"  ,
         act."Activity Name" ,
         act."Activity Type" "Activity Label",
         act."Activity Start  Time" ,
         act."Activity End Time" ,
         act.EstCrdHrs ,
         act."Activity Duration" ,
         act."Base Cost" ,
         d."User First Name" ,
         d."User Last Name" ,
         d."User Country" ,
         d."User Org" ,
         d."OptEmp_Txt1"  "Global Discipline",
         d."OptEmp_Txt2"  [Financial BU],
         d."OptEmp_Txt3" [Operational BU Desc],
         d."OptEmp_Txt4" as 'Operational BU Code',
         d."User Global ID" as 'Employee Number',
         d."User Notes" as 'Local Employee ID',
         d."User Status",
         d."User Memo" as 'Company',
         d."User Integer" as 'ICS code',
         d."User Code" as 'Global Grade',
         d."User Org Code" "User Org Code",
         d."Mgr First Name" + ' ' + d."Mgr  Last Name" as 'Manager Name',
         d."Registration Status" ,
         d."Attendance Status",
         d."User Email",
         d."HR_SBU" ,
         d.[Global L&D category] ,
         d.[Learning hours],
         d.[Content Owner],
         d.[Delivery Mix],
         d.[Delivery Type],
         act.School AS 'Role Curriculum',
         act.[Facility],
         act.[Currency],
         d."User First Name" +' '+d."User Last Name" as 'User Name',
         d."User Global ID" as 'UserId',
         d.[User Job],
         d.[SessionRating],
         act.[Optional Information Text 3] AS 'Technology',
         act.MediaTypeName AS 'IndustryCategory',
         d.Fresher_identification AS 'College_Hire',
         act.[Optional Information Text 2] AS 'Product Name',
         CAST(d."Learning hours" / 8 AS DECIMAL(11,2))  as 'PMD Hours',
         CASE WHEN act.MediaTypeName IN ('Test','Real','Qualified Program','Local Program') 
                THEN act.MediaTypeName ELSE NULL END AS 'MediaTypeName',
         d.ADJ_SBU AS 'Adj_SBU',
         CAST(act.[Float] AS DECIMAL(11,2)) AS 'Facilitator Rating',
        CAST(act.Money AS NUMERIC) AS 'Response Count'
FROM

    (SELECT Attempt.Attempt_PK ,REPLACE(CONVERT(VARCHAR(95), Attempt.Note),',',' ') as [Note]   ,fact.ID 
              ,(CASE  WHEN ( ConType.ConType_Name IS NULL)   THEN 'Undefined'
                 ELSE ConType.ConType_Name  END)    [School]
              , (CASE WHEN ISNULL(MediaType.MedType_Name,'') <> 'Local Program'
              THEN 'Global'  
              WHEN ISNULL(MediaType.MedType_Name,'') = 'Local Program' AND ISNULL(ConType.ConType_Name,'') <>'External'                  
                THEN 'Local' 
                WHEN ISNULL(MediaType.MedType_Name,'') = 'Local Program' AND ISNULL(ConType.ConType_Name,'') = 'External'                    
                THEN 'External'                                                                                                          
                ELSE '' END ) [Content Owner]
              ,     (       CASE    WHEN    act.ActivityLabel IN ('ILT class', 'session', 'course', 'ILT course', 'Class', 'Virtual Course', 'Virtual session', 'Virtual Class')    
                            THEN 'Classroom'
                            WHEN    act.ActivityLabel IN ('Curriculum', 'Certification')                    THEN 'Blended'
                            WHEN    act.ActivityLabel IN ('Exam','Rapid eLearning')                         THEN 'eLearning'
                            ELSE    'eLearning'
                    END
                )   [Delivery Mix]
              ,     (
                    CASE    WHEN    ConType.ConType_Name NOT IN ('regional','SkillSoft eLearning','Regional - Onboarding',' academy', 'Regional - Process Training', 'external')  
                                    AND ( 
                                        act.ActivityLabel IN ('course','ILT course') 
                                        OR ISNULL(DimLoc.LocFacilityName, '') IN (' University (India campus)',' University (Les Fontaines campus)',' University (NA campus)') 
                                    )
                                                                                                                THEN 'Campus'
                            WHEN    ConType.ConType_Name NOT IN ('regional', 'SkillSoft eLearning','Regional - Onboarding', ' academy', 'Regional - Process Training', 'external')
                                    AND 
                                    (
                                        ISNULL(DimLoc.LocFacilityName, '') NOT IN (' University (India campus)',' University (Les Fontaines campus)',' University (NA campus)') 
                                        OR ISNULL(DimLoc.LocFacilityName, '')  = ''
                                    ) 
                                    AND act.ActivityLabel IN ('Session', 'ILT class', 'Class')                  THEN 'Glocal'

                            WHEN    (
                                        (
                                            act.ActivityLabel IN ('Mobile Nuggets', 'Virtual Classroom Replay', 'Exam')
                                            OR (act.ActivityLabel='Virtual Session' AND ISNULL(act.EndDt, '') = '')
                                        )
                                    )

                                    OR act.ActivityLabel IN ('Web Based Learning', 'Quick Assessment','Rapid eLearning')
                                                                                                                THEN 'Web Based Learning'

                            WHEN    act.ActivityLabel IN ('virtual Session', 'virtual course', 'Virtual class') THEN 'Virtual'

                            WHEN    act.ActivityLabel IN ('knowledge object','document','Book','audio','video')
                                                                                                                THEN 'Other Online Resources'

                            WHEN    ConType.ConType_Name  in ('regional', ' academy','Regional - Onboarding','External','local','SkillSoft eLearning', 'Regional - Process Training') 
                                    AND act.ActivityLabel IN ('ILT class' ,'Session' ,'Course' ,'ILT course', 'Class')  
                                                                                                                THEN 'Local'

                            WHEN    act.ActivityLabel='Curriculum'                                              THEN 'Curriculum'

                            WHEN    act.ActivityLabel='Certification'                                           THEN 'Certification'

                            ELSE                                                                                     ''

                    END
                )   [Delivery Type]
              ,     (
                    CASE
                            WHEN    act.ActivityLabel IN ('ILT class', 'session', 'course', 'ILT course', 'Class') Then 'Classroom'
                            WHEN    act.ActivityLabel IN ('Rapid eLearning') Then 'Virtual Learning'
                            WHEN 
                                    (
                                        act.ActivityLabel not in ('ILT class','session','course','ILT course','Curriculum','Certification')
                                        OR year(act.EndDt) <> '2013'
                                    )
                                    OR
                                    (
                                        (
                                            act.ActivityLabel IN ('ILT class' ,'session' ,'course' ,'ILT course') 
                                            OR year(act.EndDt) = '2013'
                                        ) 
                                        AND
                                        act.ActivityLabel ='Virtual Session'
                                    )
                                    OR
                                    ( 
                                        (

                                            act.ActivityLabel IN ('Mobile Nuggets','Audio','Video', 'Virtual Session', 'Web Based Learning', 'Book' , 'Knowledge Object' , 'Document') 
                                            AND
                                            (
                                                act.ActivityLabel not in ('ILT class','session','course','ILT course','Curriculum','Certification')
                                                OR year(act.EndDt) <> '2013'
                                            ) 
                                            AND
                                            (
                                                (
                                                    (
                                                        act.ActivityLabel = 'Virtual Session' AND year(act.EndDt) is NULL
                                                    ) 
                                                    OR 
                                                    (
                                                        act.ActivityLabel = 'Virtual Session' AND ISNULL(act.EndDt, '') = ''
                                                    ) 

                                                    OR act.ActivityLabel IN ('Virtual Session' , 'Book' , 'Knowledge Object' , 'Document', 'Web Based Learning') 
                                                    AND ConType.ConType_Name = 'External'
                                                )
                                            )
                                        )
                                    )
                                                                                                                Then 'Virtual Learning'

                            Else                                                                                     '' 
                    END
                )   [Global L&D category]
              , (Case
                      WHEN isnull(act.EstCrdHrs,0) > 0 
                       Then act.EstCrdHrs
                       Else
                        isnull(act.[EstDurHours],0)

                End) [Learning hours]
              ,'' AS [Location]
              ,'' AS [Facility]
              ,REPLACE(CONVERT(VARCHAR(95), attnd.name),',',' ')         [Attendance Status]
              ,REPLACE(CONVERT(VARCHAR(95), Success.name),',',' ')   [Success]
              ,act.ID        [ActivityID]
              ,act.ActivityFK    [Activity PK]
              ,REPLACE(CONVERT(VARCHAR(95), emp.PrimaryOrgName ),',',' ') AS [User  OrgName]
              ,'' AS [Activity Name]
              ,'' AS [Activity Label]
              ,'' AS [Activity Code]
              ,'' AS [Activity Start  Time]
              ,act.enddt AS [Activity End Time]
              ,fact.Score   [Score]
              ,'' AS [RegDeadlineDt]
              ,'' AS [RegCnclDeadlineDt]
              ,'' AS [Activity Duration]
              ,'' AS [EstCrdHrs]
              ,'' AS [MinCapacity]
              ,'' AS [MaxCapacity]
              ,'' AS [Self Report Training]
              ,'' AS [Currency]
              ,'' AS [Base  Cost]
              ,'' AS [Late Cancellation Cost]
              ,'' AS [No Show Fee]
              ,REPLACE(CONVERT(VARCHAR(95), emp.OptEmp_Txt1),',',' ')       as [HR_SBU]
              ,REPLACE(emp.ID,',','.')    AS [User  Number]
              ,REPLACE(emp.EmpFK,',','.')     [User EmpPK]
              ,REPLACE(emp.EmpCode,',','') [User Code]
              ,REPLACE(emp.EmpStat,',','')     AS [User Status]
              ,REPLACE(emp.EmpNo,',','')         AS [User Global ID]
              ,REPLACE(iwcU.Usr_Name,',','.')                             AS [User Name]  
              ,REPLACE(CONVERT(VARCHAR(95), emp.EmpFName ),',',' ') AS [User First Name]
              ,REPLACE(CONVERT(VARCHAR(95), emp.EmpLName ),',',' ') AS [User Last Name]
              ,REPLACE(CONVERT(VARCHAR(95), emp.EmpCity ),',',' ')   AS [User City]
              ,REPLACE(CONVERT(VARCHAR(95), UPPER(emp.EmpCntry)  ),',',' ') AS [User Country]
              ,REPLACE(CONVERT(VARCHAR(95), emp.EmpEmail ),',',' ')AS [User Email]
              ,REPLACE(CONVERT(VARCHAR(95), JT.Job_Name ),',',' ')   AS [User Job]
              ,REPLACE(CONVERT(VARCHAR(95), emp.PrimaryOrgName ),',',' ') AS [User Org]
              ,REPLACE(CONVERT(VARCHAR(95), DimOrg.Code ),',',' ')                 AS [User Org Code]  
              ,REPLACE(CONVERT(VARCHAR(95), emp.OptEmp_Txt1 ),',',' ')   AS [OptEmp_Txt1]
              ,REPLACE(CONVERT(VARCHAR(95), emp.OptEmp_Txt2),',',' ')    AS [OptEmp_Txt2]
              ,REPLACE(CONVERT(VARCHAR(95), emp.OptEmp_Txt3),',',' ')    AS [OptEmp_Txt3]
              ,REPLACE(CONVERT(VARCHAR(95), emp.OptEmp_Txt4),',',' ')   AS [OptEmp_Txt4]
              ,emp.OptEmp_Ind1 AS 'Fresher_identification'
              ,emp.OptEmp_Dt1 AS 'Fresher_end_date'
              ,EMP.MgrEmpFName AS [Mgr First Name]
              ,EMP. MgrEmpLName AS [Mgr  Last Name]
              ,REPLACE(CONVERT(VARCHAR(95), tblOptEmp.OptEmp_Memo1),',',' ')  AS [User Memo]
              ,REPLACE(CONVERT(VARCHAR(95), tblOptEmp.OptEmp_Int1  ),',',' ') AS [User Integer]
              ,REPLACE(CONVERT(VARCHAR(95), tblemp.Emp_Note),',',' ')   AS [User Notes]
              ,CONVERT(smalldatetime, sd.Date) AS [Attempt Start Date]
              ,REPLACE(CONVERT(VARCHAR(95), sd.DayName),',',' ')  [Attempt Start Date Day] 
              ,CONVERT(smalldatetime, ed.Date) AS [Attempt Completion Date]
              ,REPLACE(CONVERT(VARCHAR(95), ed.DayName),',',' ') [Attempt Completion Date Day] 
              ,REPLACE(CONVERT(VARCHAR(95), RegStatus.name  ),',',' ')  [Registration Status]
              ,REPLACE(CONVERT(VARCHAR(95), CompletionStatus.name),',',' ') [Completion Status],
               ApprovalTrans.[RegistrantApproval Type],
                ApprovalTrans.RegistrantApprLevel                   ,       
                '' AS RegistrantApprName,
                ApprovalTrans.[RegistrantApproval Email],
                '' AS [RegistrantActual Approver],
                ApprovalTrans.[RegistrantActual Approver Email],
                ApprovalTrans.[RegistrantApproval Status] ,
                '' as [RegistrantApproval notes]    ,
                ApprovalTrans.RegistrantApprDate  , 
                '' as [TrainingApproval Type],
                '' AS TrainingApprLevel,
                '' AS TrainingApprName,
                ApprovalTrans.[TrainingApproval Email],
                '' AS [TrainingActual Approver],
                ApprovalTrans.[TrainingActual Approver Email],
                ApprovalTrans.[TrainingApproval Status] ,
                '' as [TrainingApproval notes]  ,
                ApprovalTrans.TrainingApprDate  ,
              RegDate.Date              AS  [RegistrationDate]
              ,CancelDate.Date              AS [CancellationDate]
              , Enroller.Emp_PK     [EnrollerFK]
              ,REPLACE(CONVERT(VARCHAR(95),Enroller.Emp_LName),',','')          AS   [Enroller LName]
              ,REPLACE(CONVERT(VARCHAR(95),Enroller.Emp_FName),',','')          AS  [Enroller FName]
             , case when isnull(emp.[OptEmp_Txt1],'') = 'APPS1-FSGBU' then 'APPS1-FSGBU'
                    else emp.[OptEmp_Txt1]
                end as 'ADJ_SBU'
                , (
                    CASE    
                        WHEN ApprovalTrans.[RegistrantApproval Status] = 'Not Approved' 
                                OR ApprovalTrans.[TrainingApproval Status] = 'Not Approved' THEN 'Rejected Approval'
                        WHEN CancelDate.Date < act.RegCnclDeadlineDt THEN 'Cancellation within period'
                        WHEN CancelDate.Date > act.RegCnclDeadlineDt THEN 'Late Cancellation'
                    END
                  ) AS [Cancelled - Info]
                  ,act.Txt1 as [SessionRating]      



        FROM    factAttempt fact WITH(NOLOCK)       

        LEFT OUTER JOIN Analytics.FactActivityAttemptTransactions RegTrans WITH(NOLOCK) 
                ON RegTrans.FactActivityAttemptId=FACT.ID




                LEFT OUTER JOIN tbl_tmx_attempt Attempt WITH(NOLOCK)  
                        ON fact.AttemptFK=Attempt.Attempt_PK
            LEFT OUTER JOIN dbo.dimActivity AS act WITH(NOLOCK)  
                        ON act.ID = fact.ActivityID 
                LEFT OUTER JOIN TBL_TMX_Activity as Activity WITH(NOLOCK)  
                        ON Activity_PK=Act.ActivityFK  and Activity.Activity_PK>0
                LEFT OUTER JOIN dbo.dimUser AS emp WITH(NOLOCK)  
                        ON emp.ID = fact.UserID
                LEFT OUTER JOIN tblemp tblemp WITH(NOLOCK)  
                        ON tblemp.Emp_PK=emp.EmpFK 
                LEFT OUTER JOIN iwc_Usr iwcU WITH(NOLOCK) 
                        ON tblemp.Emp_PK = iwcU.Usr_EmpFK 
                LEFT OUTER JOIN TBL_TMX_ActMetaData ActMeta WITH(NOLOCK)  
                        ON Act.ActivityFK=ActMeta.ActivityFK
                LEFT OUTER JOIN MedType  MediaType WITH(NOLOCK) 
                        ON MediaType.MedType_PK = ActMeta.MedTypeFK
                LEFT OUTER JOIN ConType ConType WITH(NOLOCK)  
                        ON ConType.ConType_PK=ActMeta.ConTypeFK
                LEFT OUTER JOIN factResourceLocation factResLoc WITH(NOLOCK)  
                        ON factResLoc.ActivityID=fact.ActivityID
                LEFT OUTER JOIN DimLoc WITH(NOLOCK)  
                        ON DimLoc.ID=factResLoc.LocID
                LEFT OUTER JOIN dimAttendanceStatus attnd WITH(NOLOCK)  
                        ON fact.AttendanceStatusID=attnd.ID
                LEFT OUTER JOIN dimSuccess Success WITH(NOLOCK)  
                        ON Success.ID = fact.SuccessID                  
                LEFT OUTER JOIN dimRegistrationStatus  RegStatus WITH(NOLOCK) 
                        ON RegStatus.ID=fact.RegistrationStatusID
                LEFT OUTER JOIN dimCompletionStatus CompletionStatus WITH(NOLOCK) 
                        ON CompletionStatus.ID=fact.CompletionStatusID
                LEFT OUTER JOIN  vwdimStartDate  sd WITH(NOLOCK)  
                        ON fact.StartDtID = sd.DateID                                           
                LEFT OUTER JOIN  vwdimEndDate  ed WITH(NOLOCK)  
                        ON fact.EndDtID = ed.DateID
                LEFT OUTER JOIN DimDate RegDate WITH(NOLOCK)   
                        ON  fact.RegDtID=RegDate.DateID
                LEFT OUTER JOIN DimDate CancelDate WITH(NOLOCK)  
                        ON  fact.CancellationDtID=CancelDate.DateID
                LEFT OUTER JOIN TBLEMP Enroller WITH(NOLOCK)    
                        ON  Enroller.Emp_PK=fact.EnrollerFK                 
                LEFT OUTER JOIN (

                select  ApprovalTrans.RegTransFK,
            REPLACE(CONVERT(VARCHAR(95),Approval2.ApprType),',','') as [RegistrantApproval Type],
            REPLACE(CONVERT(VARCHAR(95),Approval2.Ordinal),',','') AS RegistrantApprLevel ,         
            REPLACE(CONVERT(VARCHAR(95),Approver2.EmpEmail),',','') as [RegistrantApproval Email],
            REPLACE(CONVERT(VARCHAR(95),ActualApprover2.EmpEmail),',','') as [RegistrantActual Approver Email],
            REPLACE(CONVERT(VARCHAR(95),BIP_MyLearning_ApprStatus2.ApprStatus_Name ),',','')  AS [RegistrantApproval Status] ,
            CONVERT(smalldatetime, Approval2.ActionDt, 120) AS RegistrantApprDate  ,    
            REPLACE(CONVERT(VARCHAR(95),Approver.EmpEmail),',','') as [TrainingApproval Email],
            REPLACE(CONVERT(VARCHAR(95),ActualApprover.EmpEmail),',','') as [TrainingActual Approver Email],
            REPLACE(CONVERT(VARCHAR(95),BIP_MyLearning_ApprStatus.ApprStatus_Name),',','')   AS [TrainingApproval Status] ,
            CONVERT(smalldatetime, Approval.ActionDt, 120) AS TrainingApprDate
            from    (select RegTransFK,max(ApprovalFK1) as ApprovalFK1 ,max(ApprovalFK2) as ApprovalFK2 from 
                                    (
                                        select RegTransFK,null as ApprovalFK1,ApprovalFK as ApprovalFK2
                                        from TBL_TMX_ApprTransAssociation ApprTrans
                                                inner join TBL_TMX_EmpActApproval ActApproval
                                            on ApprTrans.ApprovalFK=ActApproval.EmpActApproval_PK
                                        where ApprType=-2

                                    union all

                                        select RegTransFK,ApprovalFK as ApprovalFK1 , null as ApprovalFK2
                                            from TBL_TMX_ApprTransAssociation ApprTrans
                                                    inner join TBL_TMX_EmpActApproval ActApproval
                                        on ApprTrans.ApprovalFK=ActApproval.EmpActApproval_PK
                                        where ApprType=-1
                                        ) t
                                        Group by RegTransFK) ApprovalTrans 
            LEFT OUTER JOIN TBL_TMX_EmpActApproval Approval  
                    ON ApprovalTrans.ApprovalFK1 = Approval.EmpActApproval_PK
            LEFT OUTER JOIN DimUser Approver
                    ON Approval.ApproverFK=Approver.EmpFK
            LEFT OUTER JOIN DimUser ActualApprover
                    ON Approval.ActualApproverFK=ActualApprover.EmpFK
            LEFT OUTER JOIN 
            (
                select [ApprStatus_ID],[ApprStatus_Name] from 
                   ( values(0,'Waiting for approval'),(1,'Approved'),(2,'Not Approved')

                   ) as t ([ApprStatus_ID],[ApprStatus_Name])

            )BIP_MyLearning_ApprStatus   
                    ON Approval.Status = BIP_MyLearning_ApprStatus.ApprStatus_ID 
            LEFT OUTER JOIN TBL_TMX_EmpActApproval Approval2     
                    ON ApprovalTrans.ApprovalFK2 = Approval2.EmpActApproval_PK
            LEFT OUTER JOIN DimUser Approver2
                    ON Approval2.ApproverFK=Approver2.EmpFK
            LEFT OUTER JOIN DimUser ActualApprover2
                    ON Approval2.ActualApproverFK=ActualApprover2.EmpFK
            LEFT OUTER JOIN 
            (
                select [ApprStatus_ID],[ApprStatus_Name] from 
                   ( values(0,'Waiting for approval'),(1,'Approved'),(2,'Not Approved')

                   ) as t ([ApprStatus_ID],[ApprStatus_Name])       
            )

             as BIP_MyLearning_ApprStatus2 
                    ON Approval2.Status = BIP_MyLearning_ApprStatus2.ApprStatus_ID

                ) ApprovalTrans 
                            ON ApprovalTrans.RegTransFK=RegTrans.RegTransactionSourceId



        LEFT OUTER JOIN bridgeUserOrg UserPrimaryOrg
                        on emp.EmpFK=UserPrimaryOrg.EmpFK and UserPrimaryOrg.IsPrimary= 1 
        LEFT OUTER JOIN tblOptEmp tblOptEmp 
                        on tbloptemp.OptEmp_EmpFK=tblemp.Emp_PK
        LEFT OUTER JOIN DimOrg
                        ON DimOrg.OrgID=UserPrimaryOrg.OrgID
        LEFT OUTER JOIN JOB JT WITH (NOLOCK)
                            ON emp.PrimaryJobFK = JT.Job_PK


        WHERE (act.enddt >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) or act.enddt is null )
        AND (ed.YearNumber = YEAR(GETDATE()) OR ed.Date is null)
        AND (act.enddt >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0) OR sd.YearNumber = YEAR(GETDATE()) OR ed.YearNumber = YEAR(GETDATE()) )
        ) d

        JOIN

        (
            SELECT  
                Act.Code AS [Activity Code],
                REPLACE(act.EstDur / 3600,',','.') AS [Activity Duration],
                Act.EndDt AS [Activity End Time], 
                lbl.ActLabel_Name AS [Activity Type], 
                Act.ActivityName AS [Activity Name] , 
                REPLACE(Act.Activity_PK,',','.')  AS [Activity PK], 
                coalesce(Prntact.Activity_PK,Offeredby.Activity_PK) as [ParentActivityID],
                Act.StartDt AS [Activity Start  Time], 
                Act.CostBase AS [Base Cost], 
                Currency.Name AS [Currency], 
                Act.EstCrdHrs AS [EstCrdHrs], 
                REPLACE(CONVERT(VARCHAR(95),Fac.Fac_Name),',',' ') AS [Facility],
                ActOpt.Float1 AS [Float],
                ActOpt.Ind1,
                Act.CostLateCncl AS [Late Cancellation Cost], 
                REPLACE(CONVERT(VARCHAR(95),Loc.Loc_Name),',',' ') AS [Location], 
                Act.MaxCapacity AS [MaxCapacity], 
                MediaType.[MedType_Name] as  MediaTypeName,
                Act.MinCapacity AS [MinCapacity], 
                ActOpt.Money1 AS [Money],
                Act.CostNoShow AS [No Show Fee], 
                REPLACE(CONVERT(VARCHAR(95),ActOpt.Txt2),',',' ') AS [Optional Information Text 2],
                REPLACE(CONVERT(VARCHAR(95),ActOpt.Txt3),',',' ') AS [Optional Information Text 3],
                Act.RegCnclDeadlineDt AS [RegCnclDeadlineDt], 
                Act.RegDeadlineDt AS [RegDeadlineDt], 
                CASE 
                        WHEN REPLACE(act.code, '_', '-') LIKE 'AT-%'        THEN 'Austria'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'AU-AUC-%'    THEN 'Australia CS/TS'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'AU-BPO-%'    THEN 'Australia BPO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'U-%'         THEN 'University'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-UK%'     THEN 'SOGETI UK'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-NA-%'    THEN 'SOGETI NA'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'BE-%'        THEN 'Belgium'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CE-%'        THEN 'Central Europe'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CN-%'        THEN 'China'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'DK-%'        THEN 'Denmark'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'EE-%'        THEN 'Eastern Europe'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'FI-%'        THEN 'Finland'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'FS-%'        THEN 'Financial Services GBU'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GD-%'        THEN 'Group Delivery'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-LD-%'     THEN 'Global Learning'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'IN%'         THEN 'India'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'NA-%'        THEN 'North America'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'NL-%'        THEN 'Netherlands'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'NO-%'        THEN 'Norway'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SE-%'        THEN 'Sweden'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SKL-%'       THEN 'SkillSoft'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'UK-%'        THEN 'United Kingdom'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CL-%'        THEN 'Chile'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SP-%'        THEN 'Spain'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'FR-%'        THEN 'France'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'IT-%'        THEN 'Italy'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'AU-U-%'      THEN 'Australia CS/TS'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CC-%'        THEN ' Consulting'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CZ-%'        THEN 'Czech Republic'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'I3-%'        THEN 'Global Learning'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'PH-%'        THEN 'Philippines' 
                        WHEN REPLACE(act.code, '_', '-') LIKE 'PL-BPO-%'    THEN 'Poland BPO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'PL-ITO-%'    THEN 'Poland ITO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-BE-%'    THEN 'Sogeti - Belgium'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-DK-%'    THEN 'Sogeti - Denmark'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-FR-%'    THEN 'Sogeti - France'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-DE-%'    THEN 'Sogeti - Germany'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-NL-%'    THEN 'Sogeti - Netherlands'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-NO-%'    THEN 'Sogeti - Norway'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SOG-SE-%'    THEN 'Sogeti - Sweden'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'AR-%'        THEN 'Argentina'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'PT-%'        THEN 'Portugal'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'Nord%'       THEN 'Nordics'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'DE-%'        THEN 'Germany'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GS-%'        THEN 'Group Sales'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CERT-EXT-%'  THEN 'External certifications'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'RO-%'        THEN 'Romania'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GT-%'        THEN 'Guatemala'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'MA%'         THEN 'Morocco'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-APPS1%'   THEN 'Global Apps1'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-Apps2%'   THEN 'Global Apps2'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-BPO%'     THEN 'Global BPO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-ACA%'     THEN 'Global Academy'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'BR-BPO%'     THEN 'Brazil BPO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'BR-CPM%'     THEN 'CPM Braxis'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'BR-PP%'      THEN 'Brazil BPO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'BR-PROF%'    THEN 'Brazil BPO'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'S-%'         THEN 'France'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'MX-%'        THEN 'Mexico'   
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-INFRA-%'  THEN 'Global-Infra'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CO-%'        THEN 'Colombia'         
                        WHEN REPLACE(act.code, '_', '-') LIKE 'PLS-%'       THEN 'PluralSight'      
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-FIN-%'    THEN 'Group Finance'        
                        WHEN REPLACE(act.code, '_', '-') LIKE 'GL-HR-%' THEN 'Group HR'
                        WHEN REPLACE(act.code, '_', '-') LIKE 'SG-%'        THEN 'Singapore' 
                        WHEN REPLACE(act.code, '_', '-') LIKE 'CRP-%'       THEN 'Coorpacademy'
                WHEN REPLACE(act.code, '_', '-') LIKE 'PL-NSC-%'    THEN 'Poland - NSC' 
                WHEN REPLACE(act.code, '_', '-') LIKE 'PES-%'       THEN 'Percipio' 
                WHEN REPLACE(act.code, '_', '-') LIKE 'HU-%'        THEN '  Hungary'        
                 --20190708 : MY : Adding the new region 'Harvard'
                WHEN REPLACE(act.code, '_', '-') LIKE 'HMM-%'   OR  REPLACE(act.code, '_', '-') LIKE 'HBP-%' THEN 'Harvard'     

                END                                                                                                                                  AS [Region],
                ContentType.ConType_Name AS [School],
                Act.UseType AS [Self Report Training],
                REPLACE(CONVERT(VARCHAR(95),ActOpt.Txt1),',',' ') AS [Optional Information Text 1],
                REPLACE(CONVERT(VARCHAR(95),ActOpt.Txt4),',',' ') AS [Optional Information Text 4],
                Vendor.Ven_Name as Vendor_Name

        FROM    dbo.TBL_TMX_Activity AS Rootact 
                RIGHT OUTER JOIN dbo.TBL_TMX_Activity AS Act
                    LEFT OUTER JOIN dbo.TBL_TMX_ActCBT ON Act.Activity_PK = dbo.TBL_TMX_ActCBT.ActivityFK
                    LEFT OUTER JOIN dbo.TBL_TMX_ActLinks as OfferedByAct on OfferedByAct.LinkedActFK = act.activity_pk and OfferedByAct.LinkType = 2 and OfferedByAct.ActivityFK > 0 
                    LEFT OUTER JOIN dbo.ActLabel AS lbl ON Act.ActivityLabelFK = lbl.ActLabel_PK 
                    ON Rootact.Activity_PK = Act.RootActivityFK
                LEFT OUTER JOIN dbo.ActLabel AS Parent_lbl
                    INNER JOIN dbo.TBL_TMX_Activity AS Prntact ON Parent_lbl.ActLabel_PK = Prntact.ActivityLabelFK 
                    ON Act.PrntActFK = Prntact.Activity_PK
                LEFT OUTER JOIN dbo.ActLabel AS Offeredby_lbl
                    INNER JOIN dbo.TBL_TMX_Activity AS Offeredby ON Offeredby_lbl.ActLabel_PK = Offeredby.ActivityLabelFK 
                    ON OfferedByAct.ActivityFK = Offeredby.Activity_PK
                LEFT OUTER JOIN dbo.TBL_TMX_ActMetaData AS ActMeta ON Act.Activity_PK = ActMeta.ActivityFK
                LEFT OUTER JOIN dbo.ConType AS ContentType ON ContentType.ConType_PK = ActMeta.ConTypeFK
                LEFT OUTER JOIN dbo.TBL_TMX_ActMetaData AS ParentActMeta ON coalesce(Prntact.Activity_PK,Offeredby.Activity_PK) = ParentActMeta.ActivityFK
                LEFT OUTER JOIN dbo.ConType AS ParentContentType ON ParentContentType.ConType_PK = ParentActMeta.ConTypeFK
                LEFT OUTER JOIN MedType  ParentMediaType ON ParentMediaType.MedType_PK = ParentActMeta.MedTypeFK
                LEFT OUTER JOIN dbo.TBL_TMX_ActOpt AS ParentActOpt ON coalesce(Prntact.Activity_PK,Offeredby.Activity_PK) = ParentActOpt.ActivityFK 
                LEFT OUTER JOIN dbo.TBL_LMS_Currency AS Currency ON Act.CurrencyFK = Currency.Currency_PK
                LEFT OUTER JOIN dbo.TBL_TMX_ActLoc AS ActLoc ON Act.Activity_PK = ActLoc.ActivityFK
                LEFT OUTER JOIN dbo.Loc ON ActLoc.LocFK = dbo.Loc.Loc_PK
                LEFT OUTER JOIN dbo.Fac ON dbo.Loc.Loc_FacFK = dbo.Fac.Fac_PK
                LEFT OUTER JOIN dbo.TBL_TMX_ActOpt AS ActOpt ON Act.Activity_PK = ActOpt.ActivityFK
                LEFT OUTER JOIN dbo.TBL_TMX_RegTrack AS RegTrck ON Act.Activity_PK = RegTrck.ActivityFK
                LEFT OUTER JOIN dbo.TBL_LMS_userLang AS Lang ON ActMeta.LangFK = Lang.UserLang_PK
                LEFT OUTER JOIN dbo.TBL_TMX_ActAud AS ActAudience ON Act.Activity_PK = ActAudience.ActivityFK
                LEFT OUTER JOIN dbo.TBL_TMX_Audience AS Audience ON ActAudience.AudienceFK = Audience.Aud_PK
                LEFT OUTER JOIN dbo.TBL_ADM_DomAct AS DomAct ON Act.Activity_PK = DomAct.DomAct_ActFK AND DomAct.DomAct_PrmyInd = 1
                LEFT OUTER JOIN dbo.Org ON DomAct.DomAct_DomainFK = dbo.Org.Org_PK
                LEFT OUTER JOIN dbo.tblEmp AS Emp ON Act.OwnerEmpFK = Emp.Emp_PK
                LEFT OUTER JOIN dbo.EvtStat ON ActMeta.ActStatFK = dbo.EvtStat.EvtStat_PK
                LEFT OUTER JOIN dbo.TBL_TMX_ActVen ActVen ON ActVen.ActivityFK = Act.Activity_PK
                LEFT OUTER JOIN dbo.Ven Vendor ON ActVen.VenFK=Vendor.Ven_PK
                LEFT OUTER JOIN MedType  MediaType ON MediaType.MedType_PK = ActMeta.MedTypeFK

        ) act
        ON act."Activity PK"  = d."Activity PK"   

WHERE
    (YEAR("Attempt Completion Date")=2019 OR YEAR("Attempt start date") = 2019)
    AND [Registration Status] IN('Completed','In Progress')
    AND [Activity Type] NOT IN ( 'Course', 'ILT Course','Curriculum', 'Certification', 'Virtual Course', 'Book')
    AND act.[Self Report Training]  = 0
        AND [User Country] NOT IN ('Administrator', 'External', 'Test')



GROUP BY d.[User EmpPK],act.[Activity PK],[Global L&D category],[Learning hours],[Content Owner],[Delivery Mix],[Delivery Type],Region,act.School,act.[Activity Code],
act.[Activity Name],[Activity Type],act.[Activity Start  Time],act.[Activity End Time],act.Facility,act.EstCrdHrs,act.[Activity Duration],[Base Cost],act.Currency,d.[User First Name],
d.[User Last Name],[User Name],d.[User Country], d.[User Org],d.OptEmp_Txt1,d.OptEmp_Txt2,d.OptEmp_Txt3,d.OptEmp_Txt4,d.[User Global ID], d.[User Notes],d.[User Status],d.[User Memo],
d.[User Integer],d.[User Code],d.[User Org Code],d.[Mgr First Name],d.[Mgr  Last Name],d.[Registration Status],d.[Attendance Status],d.[User Email],d.[User Job],d.HR_SBU,
d.SessionRating,act.[Optional Information Text 3],d.Fresher_identification,act.[Optional Information Text 2],
act.MediaTypeName,d.ADJ_SBU,act.[Float],act.[Money]
) Query_Set


 group by [User Country] 
 order by [User Country]

查询将花费超过15分钟的时间来执行,并且该数据库是实时数据库。请建议我是否可以尝试其他方法来提高性能,例如临时表或其他内容。
我已编辑问题以发布确切的代码。该查询需要23分钟才能执行。我需要修复一下性能。
请帮忙。

2 个答案:

答案 0 :(得分:0)

您在每个子查询中使用GROUP BY,但没有诸如SUM()等之类的聚合函数。

您将在尽可能使用不重复的地方代替过滤器(WHERE子句)。 还有...为什么您没有条件加入表?

(select distinct column 1, column 2 ....column n  
 from table 1, table 2, ..table n)

以上是笛卡尔联接。作为回报,您将获得table1 x table2 x ... tableN行,并且您正在构建其中的两个并将它们连接在一起。更不用说您锁定了所有知道谁时间的表。

没有任何示例数据,很难说出您想要实现什么。提供更多详细信息。

答案 1 :(得分:-1)

子查询影响您的表现。分离这两个查询,并使用类似视图的方法来对第一个查询进行定位,然后在该视图上运行外部查询。我想这不是代码生成的查询。请提供更多信息。