在SQL Server 2016中将小计行添加为摘要项

时间:2019-02-11 00:43:54

标签: sql sql-server

我有一个查询问题,而不是我想做的事,我想按两个字段进行求和,然后在每个字段的末尾给我一个总结,例如

这就是我所拥有的,

enter image description here

这就是我想要的

enter image description here

这是我的查询代码,对我有帮助,可以解决此问题

select  
c.Name                              as Category,
p.Record2                           as Record, 
s.SubTotal                          as [Sub Total],
s.TotalDiscount                     as [Cover],
s.TotalCharges                      as Charges,
s.Total                             as Billed,
s.PaidAmount                        as Paid,
s.DebtAmount                        as Debt,
i.Name as Insurance



 from sales  s 

    inner join status st on    st.StatusId = s.StatusId
     inner join Insurances i  on      i.InsuranceId=  s.InsuranceId 
  inner join categories c on     c.CategoryId =     s.CategoryId
  inner join Customers cu on  cu.CustomerId = s.CustomerId
 inner join people p on p.PersonId=cu.PersonId  
  inner join  CashierDetails cd on cd.CashierDetailId= s.CashierDetailId 
inner join  Cashiers ca on ca.CashierId= cd.CashierId
  inner join Users u on u.UserId= s.UserId

 --and s.InsuranceId=32                  
and  s.SalesDate >= '2019/02/09'     
and  s.SalesDate <= '2019/02/14'     

 order by   s.InsuranceId,s.CategoryId

1 个答案:

答案 0 :(得分:2)

您似乎想要分组集:

with t as (
      <your query here without order by>
     )
select Category, Record,
       sum([Sub Total]) as subtotal, sum(Cover) as cover, 
       sum(Charges) as charges, sum(billed) as billed,
       sum(paid) as paid, sum(debt)
       Insurance
from t
group by grouping sets ( (category, record, insurance), (category, insurance), (insurance) );

您可以使用coalesce()或类似的逻辑将NULL的值替换为所需的列值。