2016-07-26 97 views
0

我的查詢即時將數據分解12個月,但列'Submitted - New Business'來自另一個表。它有沒有可能按月分解?按月分選select語句

SELECT  'Eldred, Rod' AS Underwriter,     
       SUM(CASE WHEN Underwriter = 'Eldred, Rod' THEN UWReportFee ELSE 0 END) as 'UW ReportFee', 
       (SUM(CASE WHEN Underwriter = 'Eldred, Rod' THEN Fees ELSE 0 END)) - SUM(CASE WHEN Underwriter = 'Eldred, Rod' THEN UWReportFee ELSE 0 END) as 'Taxes & Surcharges', 
       COUNT(CASE WHEN Underwriter = 'Eldred, Rod' AND PolicyType = 'New Business' THEN QuoteControlNum END) as  'Submitted - New Business', 
     /*SubQuery*/ 
       (
       SELECT COUNT(CASE WHEN Underwriter = 'Eldred, Rod' AND Type = 'New Business' THEN ControlNo END) 
       FROM  tblCalendar b 
       LEFT JOIN ClearanceReportMetrics a ON b.MonthNum=Month(a.EffectiveDate)  
       AND b.YearNum = YEAR(a.EffectiveDate) AND CompanyLine = 'Arch Insurance Company' AND YEAR(EffectiveDate)=2016 
       ) as 'Submitted - New Business' , 
     /* End of SubQuery*/ 

       b.MonthNum, 
       b.YearNum 
    FROM  tblCalendar b 
    LEFT JOIN ProductionReportMetrics a ON b.MonthNum=Month(a.EffectiveDate) 
       AND b.YearNum = YEAR(a.EffectiveDate) AND CompanyLine = 'Arch Insurance Company' AND YEAR(EffectiveDate)=2016 
       --AND a.Underwriter ='Eldred, Rod' 
    WHERE  b.YearNum = 2016 
    GROUP BY --a.Underwriter, 
       b.MonthName, 
       b.MonthNum, 
       b.YearNum  

enter image description here

,你可以在PIC看到,每個月都有相同的價值,是任何機會,以某種方式打破它沒有全光照JOIN

+0

使用相關子查詢到從外到您的一個月(a.effectivedate)加入b.month?但你需要以不同的方式別名內部查詢B表。 – xQbert

+0

謝謝。但是你有什麼好的例子嗎? – Oleg

+0

你需要加入2個grpouped查詢或分組後交叉應用。加入有什麼問題? – Serg

回答

1

試着加入分組數據集

declare @uw varchar(50) ='Eldred, Rod'; 
    declare @year = 2016; 
    declare @cn varchar(50) ='Arch Insurance Company'; 

    SELECT  @uw,     
       t1.'UW ReportFee', 
       t1.'Taxes & Surcharges', 
       t1.'Submitted - New Business', 
       t2.cnt as 'Submitted - New Business count' , 
       b.MonthNum, 
       b.YearNum 
    FROM  tblCalendar b 
    LEFT JOIN ( 
       SELECT 
       Month(EffectiveDate) as Month, 
       SUM(UWReportFee) as 'UW ReportFee', 
       (SUM(Fees) - SUM(UWReportFee) as 'Taxes & Surcharges', 
       COUNT(CASE WHEN PolicyType = 'New Business' THEN QuoteControlNum END) as 'Submitted - New Business', 
       FROM ProductionReportMetrics 
       GROUP BY Month(EffectiveDate), 
       WHERE YEAR(a.EffectiveDate) = @year AND CompanyLine = @cn AND Underwriter = @uw 
       ) t1 ON t1.Month = b.MonthNum 
    LEFT JOIN ( 
       SELECT 
       Month(EffectiveDate) as Month, 
       COUNT(ControlNo) as cnt 
       FROM ClearanceReportMetrics 
       GROUP BY Month(EffectiveDate), 
       WHERE YEAR(a.EffectiveDate) = @year AND CompanyLine = @cn AND Underwriter = @uw AND Type = 'New Business' 
       ) t2 ON t2.Month = b.MonthNum 
    WHERE  b.YearNum = 2016 
+0

令人驚歎!謝謝Serg,它工作的很棒! – Oleg