2016-08-24 152 views
1

我從動態數據透視查詢中獲取總列數有問題。 從我的代碼我得到這個結果: the result without total ,我想從32,33,34,35列合計欄,並把它列35(垂直總行列)後SQL從動態數據透視表中獲取總列數

這裏是我的代碼:

SET DATEFIRST 1; 
    DECLARE @cols AS NVARCHAR(MAX), 
    @colNames AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 

SELECT @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(DATEPART(wk,OINV.TaxDate)) 
      FROM OINV 
      WHERE YEAR(OINV.TaxDate) = 2016 AND MONTH(OINV.TaxDate) = 8 
      FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

SELECT @colNames = STUFF((SELECT DISTINCT ', ISNULL(' + QUOTENAME(DATEPART(wk,OINV.TaxDate)) +', 0) as '+ QUOTENAME(DATEPART(wk,OINV.TaxDate)) 
       FROM OINV 
       WHERE YEAR(OINV.TaxDate) = 2016 AND MONTH(OINV.TaxDate) = 8 
       FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'') 

SET @query = 'SELECT Salesman, Cabang, '+ @colNames +' 
      FROM(SELECT 
       OSLP.SlpName as Salesman, 
       OCRD.U_STEM_BP_WHSE as Cabang, 
       SUM(OINV.DocTotal) as Achiev, 
       DATEPART(wk,OINV.TaxDate) as WeekNo 
      FROM OINV 
       INNER JOIN INV1 ON INV1.DocEntry = OINV.DocEntry 
       INNER JOIN OSLP ON OINV.SlpCode = OSLP.SlpCode 
       INNER JOIN OITM ON INV1.ItemCode = OITM.ItemCode 
       INNER JOIN OMRC ON OITM.FirmCode = OMRC.FirmCode 
       INNER JOIN OCRD ON OINV.CardCode = OCRD.CardCode 
      WHERE 
       YEAR(OINV.TaxDate) = 2016 AND MONTH(OINV.TaxDate) = 8 
      GROUP BY 
       OSLP.SlpName, 
       OCRD.U_STEM_BP_WHSE, 
       OINV.TaxDate) AS a 
      PIVOT(SUM(Achiev) 
      FOR WeekNo IN (' + @cols + ')) AS pvt 
      ORDER BY Salesman ASC' 

EXECUTE(@query); 

非常感謝您的幫助,謝謝。從@Anton

使用的建議,這是更新的結果我得到: the updated result

回答

1

變化

SET @query = 'SELECT Salesman, Cabang, '+ @colNames +' 

SET @query = 'SELECT Salesman, Cabang, '+ @colNames +', ' + @SumCol32_35 + ' 

@ SubCol32_35應該像「[32] + [ 33] + [34] + [35]」

可以如果硬編碼列名是固定的,或者填入內部

SELECT @colNames = 

帶CASE ... END語句只填充相關列。

+0

好的,感謝您的建議,並且已經對我的代碼進行了測試,現在會顯示總體結果。但問題是當一列有一個值而另一列爲空或零時,總列數將返回零。示例結果更新了我的問題。 –

+0

不用擔心,請將答案標記爲「已回答」。 – Anton

+0

好吧,沒問題,但是你能幫我解釋一下我上面評論的問題嗎? –