Question

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

enter image description here

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top