如何给出带有group by且不为null的select乘法case语句的结果

时间:2018-07-06 11:08:09

标签: sql sql-server

我需要通过乘大小写语句选择数据并在这种情况下求和一个值,但是需要将第2列分组并得出这样的结果

Result of select case

如何给出不包含null和null的结果

这是我的查询,在图片中给出了此输出 查询:

select 
  expr1 as Custgroup, 
  case when YEAR(docdate) = '2013' then SUM(totalamount) else null end as '2013', 
  case when YEAR(docdate) = '2014' then SUM(totalamount) else null end as '2014', 
  case when YEAR(docdate) = '2015' then SUM(totalamount) else null end as '2015', 
  case when YEAR(docdate) = '2016' then SUM(totalamount) else null end as '2016', 
  case when YEAR(docdate) = '2017' then SUM(totalamount) else null end as '2017', 
  case when YEAR(docdate) = '2018' then SUM(totalamount) else null end as '2018' from NPHM56.dbo.arinvoiceview 
group by expr1, YEAR(docdate)

2 个答案:

答案 0 :(得分:0)

只需尝试使用“ sum”和“ group by”:

select Custgroup, sum([2013]) as [2013], sum([2014]) as [2014], ...
from (your query) as T
group by Custgroup

答案 1 :(得分:0)

您可以在case函数和Sum中移动group by expr1表达式,如下所示

select 
  expr1 as Custgroup, 
  SUM(case when YEAR(docdate) = '2013' then totalamount else 0 end) as '2013',
  SUM(case when YEAR(docdate) = '2014' then totalamount else 0 end) as '2014',
  SUM(case when YEAR(docdate) = '2015' then totalamount else 0 end) as '2015',
  SUM(case when YEAR(docdate) = '2016' then totalamount else 0 end) as '2016',
  SUM(case when YEAR(docdate) = '2017' then totalamount else 0 end) as '2017',
  SUM(case when YEAR(docdate) = '2018' then totalamount else 0 end) as '2018'
  from NPHM56.dbo.arinvoiceview 
group by expr1