2017-08-14 47 views
-1

如何在一個查詢中返回每個被保險縣的總保費和ExperienceMod,SchedureMod,TerritoryMod,EffectiveMod的平均值?如何獲得每個被保險縣的總數和每個Mod的平均值

select * 
from (SELECT Insured, 
      InsuredCounty, 
      PolicyNumber, 
      EffectiveDate, 
      PolicyType, 
      SUM(Premium) as Premium, 
      ExperienceMod, 
      ISNULL(ScheduleMod,0) as ScheduleMod, 
      TerritoryMod, 
      ISNULL(EffectiveMod,0) as EffectiveMod, 
      ROW_NUMBER() OVER (PARTITION BY Insured,PolicyNumber,Premium, TransactionType ORDER BY PolicyType DESC) as rid 
     FROM ProductionReportMetrics 
     WHERE EffectiveDate <= EOMONTH(GETDATE()) 
     AND CompanyLine = 'Arch Insurance Company' 
     AND Insured <>'Jerry''s Test' 
     AND TransactionType = 'Policy' 
     GROUP BY Insured, 
       InsuredCounty, 
       PolicyNumber, 
       PolicyType, 
       EffectiveDate, 
       experienceMod, 
       ScheduleMod, 
       TerritoryMod, 
       EffectiveMod, 
       Premium, 
       EffectiveDate, 
       TransactionType 
    ) b 
where rid = 1 
ORDER BY InsuredCounty, Premium desc, EffectiveDate 

目前的結果是這樣的:

enter image description here

但理想的結果會看起來像:

enter image description here

+0

您可以請張貼一些樣本數據和預期的o/p。 –

+0

增加了一些示例數據 – Oleg

+0

它完全不清楚你在問什麼。請把它作爲文字而不是圖像。 –

回答

0

這個怎麼樣?

WITH CTE AS 
(
    SELECT 
    InsuredCounty AS InsuredCountry 
    , Premium  AS premium 
    , ExperienceMod AS ExperienceMod 
    , SchedureMod AS SchedureMod 
    , TerritoryMod AS TerritoryMod 
    , EffectiveMod AS EffectiveMod 
    FROM ProductionReportMetrics 
    WHERE EffectiveDate <= EOMONTH(GETDATE()) 
     AND CompanyLine = 'Arch Insurance Company' 
     AND Insured <>'Jerry''s Test' 
     AND TransactionType = 'Policy' 
) 
SELECT InsuredCountry 
    , SUM(premium) AS premium 
    , AVG(ExperienceMod) AS ExperienceMod 
    , AVG(SchedureMod) AS SchedureMod 
    , AVG(TerritoryMod) AS TerritoryMod 
    , AVG(EffectiveMod) AS EffectiveMod 
FROM CTE 
GROUP BY InsuredCountry 
ORDER BY InsuredCounty, Premium desc, EffectiveDate; 
相關問題