SQL Server中的PIVOt函数

时间:2016-09-14 15:35:01

标签: sql-server

我的PIVOT函数的语法出错了,我无法找出原因。

我的查询是:

   SELECT Month_ID
    ,Key
    ,C.App_ID
    ,APP_Name
    FROM Usage C
    INNER JOIN Applications B ON C.App_ID = B.App_ID
    WHERE C.Key IN ('6853',
    '6859',
    '6861',
    '6863',
    '8580',
    '8626',
    '8639',
    '8717',
    '8721',
    '8731',
    '8737',
    '8744',
    '8754',
    '8873',
    '8876',
    '8884',
    '9014',
    '9080',
    '9083',
    '9085',
    '9097',
    '9101',
    '9115',
    '9117',
    '9353',
    '9354',
    '9358',
    '9380',
    '9383',
    '9385',
    '9411',
    '9471',
    '9514',
    '9587',
    '9594',
    '9595',
    '9598')
PIVOT(MAX(B.App_ID) FOR App_NAME IN (
"Data Management Services",
"intelliSource",
"Price Performance",
"Marketplace_Procure",
"Spend Essentials",
"Apt",
"Prov")) AS PVT

我一直得到的错误是:

  

Msg 156,Level 15,State 1,Line 38053   关键字' PIVOT'附近的语法不正确。

1 个答案:

答案 0 :(得分:2)

编辑,因为我没有这种结构,所以我无法在我身边进行测试。如果您包含表格结构和数据,则可以减少回答人员的工作量(以备将来参考)。

    SELECT
    * 
FROM

(SELECT 
    Month_ID ,Key ,C.App_ID ,APP_Name

FROM 
    Usage C 
    INNER JOIN Applications B ON C.App_ID = B.App_ID 
WHERE 
    C.Key IN ('6853', '6859', '6861', '6863', '8580', '8626', '8639', '8717', '8721', '8731', '8737', '8744', '8754', '8873', '8876', '8884', '9014', '9080', '9083', '9085', '9097', '9101', '9115', '9117', '9353', '9354', '9358', '9380', '9383', '9385', '9411', '9471', '9514', '9587', '9594', '9595', '9598')
) as source
PIVOT(MAX(B.App_ID) FOR App_NAME IN ( "Data Management Services", "intelliSource", "Price Performance", "Marketplace_Procure", "Spend Essentials", "Apt", "Prov")) AS PVT