SQL从动态数据透视表中获取总列数

时间:2016-08-24 03:30:00

标签: sql sql-server pivot-table

从动态数据透视查询中获取总列数时遇到问题。 从我的代码我得到了这个结果: the result without total ,我想要第32,33,34,35栏中的总列,并将其放在第35列(垂直总列)之后

这是我的代码:

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 个答案:

答案 0 :(得分: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语句仅填充相关列。