2014-03-19 51 views
0

使用SQL Server PIVOT後,在這裏我有查詢我的報告,也成功地執行它,但我沒有得到我的回答正確,在我的答案我想對總收據,MRN_P,問題,拒絕,Transfer_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 

,並導致我們得到了這裏總氣柱我希望所有行的總和,而不是空

enter image description here

+0

不應該有任何需要的'GROUP BY',也不是第二組的SUM'()單曲外'SELECT'子句中,因爲'PIVOT'已經執行了必要'SUM()' - 你爲什麼有那裏的人? –

回答

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 BYSUM()ISNULL() S的裏面做,因爲PIVOT已執行一個SUM()並正在執行對所有在PIVOT沒有提及列的隱性GROUP BY(這裏,)。

+0

非常感謝你達米恩.....因爲我是新來的這個, 所以,我從谷歌的幫助下做出這個代碼(有了很多瞭解:-) ...) 現在我有另一個查詢你會plz幫助我.. ?? –