【问题标题】:Can't Get the Total Value after using PIVOT in SQL SERVER Stored Procedure在 SQL SERVER 存储过程中使用 PIVOT 后无法获取总值
【发布时间】:2014-03-19 11:38:51
【问题描述】:

在这里我有查询我的报告并成功执行,但我没有正确得到答案,在我的答案中,我想要收据、MRN_P、问题、拒绝、Transfer_P 和 Transfer_M 的总数 但我没有得到图像中显示的空值....请帮助我解决我的代码不正确的地方

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

【问题讨论】:

  • 应该不需要GROUP BY,也不需要外部SELECT子句中的第二组SUM()s,因为PIVOT已经执行了必要的SUM() -为什么你有那些?

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


【解决方案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 BYISNULL()s 内部的SUM() 做什么,因为PIVOT 已经执行了SUM() 并且它正在执行一个隐式GROUP BYPIVOT 中未提及的所有列上(此处为tra_item)。

【讨论】:

  • 非常感谢 Damien .....因为我对这一切都很陌生,所以,我在 Google 的帮助下编写了这段代码(没有太多理解:-) ...)现在我还有一个问题,请您帮帮我..??
猜你喜欢
  • 1970-01-01
  • 2018-07-13
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多