在SQL中同时使用计数和求和

时间:2018-07-31 14:03:53

标签: sql sql-server

我从ms-sql的一个视图中获取以下数据。我想按 LossTypeExt 对结果进行分组,并创建一个新列付费严重程度,如下所示:

公式来计算PaidSeverity:

  paid serverity = sum(totalPiadamount)/distinct count of claims 

所以,我的最终结果应该是LossTypeExt和PaidSeverity($ amt)。任何想法或帮助将不胜感激。谢谢!

样本数据/表格:

         ClaimKey   ClaimNum    ClaimOpenDate   TransactionDate TotalLossPaid       LossTypeExt         

         2143672    2143672     2016-11-11      2016-11-16          0.00            Water   
         2143673    2143673     2016-11-15      2016-11-16          5266.00         Wind   
         2143674    2143674     2016-11-15      2016-11-16          151.55          Hail   
         2143675    2143675     2016-12-12      2016-11-16          2656.00         Water   
         2143676    2143676     2016-11-15      2016-11-16          5652.00         AOPD   
         2143677    2143677     2016-11-15      2017-11-16          4545.00         Liability   
         2143678    2143678     2018-18-16      2016-11-16          124.00          Liability 
         2143679    2143679     2018-05-15      2016-11-16          4541.00         AOPD
         2143680    2143680     2017-11-18      2016-11-16          966.00          Fire        

预期数据应如下所示:

         LossTypeExt    PaidSeverity

         Water          $amt
         Wind           $amt
         Fire           $amt
         Hail           $amt    
         AOPD           $amt
         Liability      $amt

查询:

  select LossTypeExt,
  sum(TotalLossPaid)/claims_cnt as PaidServerity 
 from dbo.vw_Financial_Transactions
cross join
 (select count(distinct claimNum) claims_cnt  from dbo.vw_Financial_Transactions ) as cnt
   group by LossTypeExt

2 个答案:

答案 0 :(得分:1)

您可以:

select LossTypeExt, 
       sum(TotalLossPaid) / claims_cnt as paid serverity 
from table cross join
     (select count(distinct claims) claims_cnt from table) as cnt
group by LossTypeExt;

答案 1 :(得分:0)

不需要计数的子查询:

select LossTypeExt, 
sum(TotalLossPaid)*1.0/ count(distinct claimKey) 
from myTable
group by LossTypeExt;