简体   繁体   中英

Need to add Grand Total for Pivot Column in SQL Server

I have this query which is working fine as expected but now I want to add a grand total and I am not sure where to add both the column A and B. Can someone please help!!

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   

As you are looking only for few company codes then you could use conditional aggregation approach.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM