简体   繁体   中英

Can't Get the Total Value after using PIVOT in SQL SERVER Stored Procedure

Here I have Query for my report and also Execute it successfully but i don't got my answer properly, In my answer I want the Total for the Receipt, MRN_P, Issue, Rejection, Transfer_P, and Transfer_M but instead of i got the null values which is shown in image....Plz Help me at where my Code is Incorrect

ALTER PROCEDURE [dbo].[DailyProcessReport] 
AS 
BEGIN


SELECT 
tra_item, 
IsNull(sum([Receipt]),0)as Receipt,
IsNull(sum([MRN_P]), 0)as MRN_P, 
IsNull(sum([Issue]), 0)as Issue, 
IsNull(sum([Rejection]), 0) as Rejection, 
IsNull(sum([Transfer_P]),0)as Transfer_P, 
IsNull(sum([Transfer_M]),0)as Transfer_M, 
[Receipt] + [MRN_P] + [Issue] + [Rejection] + [Transfer_P] + [Transfer_M] as 'Total' 

FROM 
(   
    SELECT tra_item, tra_quantity, tra_type
    FROM
    tra_master 

) as pvt

PIVOT (Sum(tra_quantity) FOR tra_type IN ([Receipt], [MRN_P], [Issue], [Rejection], [Transfer_P], [Transfer_M])) as pvt

Group by tra_item, [Receipt], [MRN_P], [Issue], [Rejection], [Transfer_P], [Transfer_M] 

END

and result we got Here in Total Column I Want summation of all rows instead of Null

在此处输入图片说明

I think that this should be sufficient:

SELECT 
  tra_item, 
  IsNull([Receipt],0)as Receipt,
  IsNull([MRN_P], 0)as MRN_P, 
  IsNull([Issue], 0)as Issue, 
  IsNull([Rejection], 0) as Rejection, 
  IsNull([Transfer_P],0)as Transfer_P, 
  IsNull([Transfer_M],0)as Transfer_M, 

  IsNull([Receipt],0)+IsNull([MRN_P], 0)+IsNull([Issue], 0)+ 
  IsNull([Rejection], 0)+IsNull([Transfer_P],0)+IsNull([Transfer_M],0) as Total
FROM 
(   
    SELECT tra_item, tra_quantity, tra_type
    FROM
    tra_master 

) as pvt

PIVOT (Sum(tra_quantity) FOR tra_type IN ([Receipt], [MRN_P], [Issue],
       [Rejection], [Transfer_P], [Transfer_M])) as pvt

I can't work out what you were trying to do with your GROUP BY and the SUM() inside of your ISNULL() s, since the PIVOT already performs a SUM() and it is performing an implicit GROUP BY on all of the columns not mentioned in the PIVOT (here, tra_item ).

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