Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在SQL中同时使用计数和求和_Sql_Sql Server - Fatal编程技术网

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

在SQL中同时使用计数和求和,sql,sql-server,Sql,Sql Server,我从ms sql中的视图中获得以下数据。我想按LossTypeExt对结果进行分组,并创建一个新的列付费严重性,如下所示: 计算付款金额的公式: paid serverity = sum(totalPiadamount)/distinct count of claims 因此,我的最终结果应该是LossTypeExt和PaidSeverity($amt)。任何想法或帮助都将不胜感激。谢谢 样本数据/表格: ClaimKey ClaimNum ClaimOpen

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

计算付款金额的公式:

  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
你可以做:

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;

不需要对计数进行子查询:

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

您的预期数据与包含预期数据的目的背道而驰-如果您可以用实际的预期数字替换
$amt
,这将非常有用,即使只有很少的数字。