PIVOT 的 FOR 部分中的表达式

Expression in FOR section of PIVOT

我正在尝试使用 PIVOT 获取每种产品的购买总重量,按列 year/month 细分。像这样:

+------------+--------+--------+--------+
| ProductKey | Jan-14 | Feb-14 | Mar-14 | Etc...
+------------+--------+--------+--------+
|         10 |   5000 |   7000 |   3000 |
|         20 |  10000 |   8000 |   6000 |
|         30 |    250 |    500 |    400 |
+------------+--------+--------+--------+

这是我第一次尝试使用 PIVOT,所以不确定是否正确:

PIVOT
(
SUM([PO_PurchaseOrderLines].[EstimatedWeight])
FOR
LEFT(DATENAME(MONTH,[PO_Date]),3) & "-" & RIGHT(YEAR([PO_Date]),2)
IN (Jan-14, Feb-14, Mar-14, Apr-14, May-14, Jun-14, Jul-14, Aug-14, Sep-14, Oct-14, Nov-14, Dec-14, Jan-15, Feb-15, Mar-15, Apr-15, May-15, Jun-15, Jul-15, Aug-15, Sep-15, Oct-15, Nov-15, Dec-15, Jan-16, Feb-16, Mar-16, Apr-16, May-16, Jun-16, Jul-16, Aug-16, Sep-16, Oct-16, Nov-16, Dec-16, Jan-17, Feb-17, Mar-17)
) AS POPivot

运行 这导致:​​

[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'LEFT'.

不能在 FOR 部分使用这样的表达式吗?还有其他不正确的地方吗?

Select *
From (
        Select ProductKey
              ,Col = format(PO_Date,'MMM-yy')
              ,EstimatedWeight
         From YourTable A
     ) A
 Pivot (sum(EstimatedWeight) For [Col] in ([Jan-14],[Feb-14],[Mar-14]) ) p

您不能在 FOR 部分中使用表达式,它必须是您尝试转换的查询中的一列。我建议执行该操作并将值分配给初始查询中的列,然后在 FOR.

下引用该列

这是请求的动态版本

Declare @SQL varchar(max) = ''
Select  @SQL = Stuff((Select ',' + QuoteName(Col) 
                       From (Select Distinct Top 100 
                                    Col=format(PO_Date,'MMM-yy')
                                   ,Ord=format(PO_Date,'yyyy-MM')
                              From  YourTable 
                              Where PO_Date>=DateAdd(MONTH,-36,DateFromParts(Year(GetDate()),Month(GetDate()),1))   -- Adjust This Value +/-
                              Order By 2
                             ) A  For XML Path('')),1,1,'') 

Select  @SQL = '
Select *
From (
        Select ProductKey
              ,Col = format(PO_Date,''MMM-yy'')
              ,EstimatedWeight
         From YourTable A
     ) A
 Pivot (sum(EstimatedWeight) For [Col] in (' + @SQL + ') ) p'
Exec(@SQL);