以 Month-YY 格式进行透视

Pivot with Month-YY format

现在我有一个 cte 可以在一长串列表中显示每位销售人员每月的总销售额。我希望使用 pivot 专门为每个月 行中列出的销售人员 以更轻松地显示每个月的总销售额。

查询:

WITH SalesCTE (Salesperson, Date, TotalSales)
AS
(
SELECT  FirstName + ' ' + LastName AS 'SalesPerson',
        CAST(YEAR(OrderDate) AS nvarchar(10)) + '-' + DateName(MONTH,OrderDate) AS 'Date',
        SUM(TotalDue)
FROM    Person.Person p
JOIN    Sales.SalesOrderHeader s
ON      p.BusinessEntityID = s.SalesPersonID
GROUP BY FirstName, LastName, OrderDate
)


SELECT  SalesPerson, 
        Date, 
        TotalSales
FROM    SalesCTE
ORDER BY Date, SalesPerson

此时输出:

David Campbell  2011-December   78223.3018
Garrett Vargas  2011-December   10254.8552
Jillian Carson  2011-December   52586.674
José Saraiva    2011-December   119678.9211
Linda Mitchell  2011-December   6167.1672
Michael Blythe  2011-December   71792.8437

理想情况下我想要这个:

                 December-11  January-12    February-12     ….
David Campbell  78223.3018  73343.3652  77431.389   
Garrett Vargas  10254.8552  176300.293  46954.6224  
Jillian Carson  52586.674   300998.1522 158997.3466 
José Saraiva    119678.9211 180684.8446 182343.3114 
Linda Mitchell  6167.1672   305145.2225 205684.0069 

列表中还有很多其他月份和销售人员,我以前从未做过这样的事情。查找枢轴几个小时,但无法了解它们的实际工作原理。

将带有原始日期的新列插入 table 到新的温度 table

SELECT *,CAST(DATES+'-01' AS DATE) ORGDATE 
INTO #NEWTABLE
FROM TEMP

现在声明变量以动态获取数据透视表的列

DECLARE @cols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + DATENAME(MONTH,ORGDATE)+'-'+RIGHT(CAST(YEAR(ORGDATE) AS
               VARCHAR(4)),2) + ']', 
              '[' + DATENAME(MONTH,ORGDATE)+'-'+RIGHT(CAST(YEAR(ORGDATE) AS VARCHAR(4)),2) + ']')
               FROM    (SELECT DISTINCT ORGDATE,[DATES] FROM #NEWTABLE) PV  
               ORDER BY ORGDATE

现在做枢轴

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT * FROM 
             (
                 SELECT NAME, DATENAME(MONTH,ORGDATE)+''-''+RIGHT(CAST(YEAR(ORGDATE)AS VARCHAR(4)),2) logdate, value 
                 FROM #NEWTABLE
             ) x
             PIVOT 
             (
                 SUM(value)
                 FOR logdate IN (' + @cols + ')
            ) p;' 

EXEC SP_EXECUTESQL @query