需要在SQL Server中为Pivot列添加Grand Total

时间:2018-02-27 06:02:22

标签: sql sql-server sql-server-2008

我有这个查询,按预期工作正常,但现在我想添加一个总计,我不知道在哪里添加A和B列。有人可以帮助!!

select *    
from     
(    
  select f_Parameter,  _company_code,ISNULL(Convert(numeric(18,2),f_value),0) as f_value ,f_Sort_Order ,convert(varchar(11), f_Mis_day,103) as f_Mis_day 
  from TEST with(NOLOCK) where convert(date, f_Mis_day,103) =   CONVERT(date,getdate()-1,103)     
) src    
pivot    
(    
 SUM(f_value)  
 for f_company_code in ([A], [B])    
) piv order by f_Sort_Order;  

输出:

f_Parameter               f_Sort_Order  f_Mis_day     A         B 
------------------------------------------------------------------------
Consumption Amount in INR     1         26/02/2018    10925.80  24495.10  
Transaction Count             2         26/02/2018    5.00      9.00

预期输出:

f_Parameter                   f_Sort_Order  f_Mis_day      A        B           Total
--------------------------------------------------------------------------------------------
Consumption Amount in INR     1             26/02/2018     10925.80 24495.10        35420.90   
Transaction Count             2             26/02/2018     5.00     9.00            14.00   

1 个答案:

答案 0 :(得分:0)

由于您只查找少数公司代码,因此您可以使用条件聚合方法。

Declare @date date = cast(dateadd(day, -1, getdate()) as date) 

SELECT 
       f_Parameter, f_Mis_day,
       SUM(CASE WHEN f_company_code = 'A' THEN f_value END) [A],
       SUM(CASE WHEN f_company_code = 'B' THEN f_value END) [B],
       SUM(f_value) Total 
FROM table t
WHERE f_Mis_day = @date 
GROUP BY f_Parameter, f_Mis_day