【问题标题】:How to get a total for each InsuredCounty and Average for each Mod如何获得每个 InsuredCounty 的总数和每个 Mod 的平均值
【发布时间】:2017-08-14 17:05:35
【问题描述】:

如何在一个查询中返回每个 InsuredCounty 的总保费和 ExperienceMod、SchedureMod、TerritoryMod、EffectiveMod 的平均值?

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

目前的结果如下:

但理想的结果应该是这样的:

【问题讨论】:

  • 能否请您发布一些示例数据和预期的o/p。
  • 添加了一些示例数据
  • 完全不清楚你在问什么。请将此作为文本而不是图像发布。

标签: sql-server tsql sql-server-2012


【解决方案1】:

这个怎么样?

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    相关资源
    最近更新 更多