在SQL SERVER存储过程中使用PIVOT后无法获取总值

时间:2014-03-19 11:38:51

标签: c# stored-procedures sql-server-2008-r2 pivot-table

我在这里查询了我的报告,并且也成功执行了但是我没有正确回答,在我的回答中我想要收据总额,MRN_P,问题,拒绝,转移_和Transfer_M ,而不是我得到了图像中显示的空值.... Plz帮助我在我的代码不正确的地方

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

我们得到的结果这里的总列我想要所有行的总和而不是Null

enter image description here

1 个答案:

答案 0 :(得分:1)

我认为这应该足够了:

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

由于GROUP BY已执行SUM(),我无法解决您ISNULL()PIVOTSUM()的问题。 GROUP BY并且它在PIVOT(此处为tra_item)中未提及的所有列上执行隐式{{1}}。