【问题标题】:SQL Server : Pivot Function ErrorSQL Server:透视函数错误
【发布时间】:2018-01-07 06:59:36
【问题描述】:

我收到以下错误:

消息 102,第 15 级,状态 1,第 2 行
'(' 附近的语法不正确。

执行此查询时:

SELECT 
    'Average Total Comp' AS AverageTotalComp, 
    [2016], [2015], [2014] 
FROM 
    (SELECT 
         DATEPART(yyyy, [Fiscal Year End Date]), 
         [Total Compensation ($)] 
     FROM 
         dbo.MDexec e) AS SourceTable
PIVOT 
    (AVG([Total Compensation ($)]) 
     FOR DATEPART(yyyy, [Fiscal Year End Date])  
         IN ([2016], [2015], [2014])) AS PivotTable;

我尝试同时使用YEARDATEPART。错误是引用第二个DATEPART 的左括号。

【问题讨论】:

    标签: sql-server tsql pivot


    【解决方案1】:

    您需要为 datepart 表达式分配一个别名并在您的 pivot 子句中使用它:

    SELECT 'Average Total Comp' AS AverageTotalComp, 
    [2016], [2015], [2014] 
    FROM (SELECT datepart(yyyy,[Fiscal Year End Date]) AS dp, 
    [Total Compensation ($)] FROM dbo.MDexec e) 
    AS SourceTable
    PIVOT (
    avg([Total Compensation ($)]) 
    FOR dp 
    IN ([2016], [2015], [2014])) AS PivotTable;
    

    【讨论】:

    • 你打败了我。
    【解决方案2】:

    您不需要Pivot 来执行此操作。试试这个方法

    SELECT AverageTotalComp = 'Average Total Comp',
           [2016] = Avg(case when year([Fiscal Year End Date]) = 2016 then [Total Compensation ($)] end), 
           [2017] = Avg(case when year([Fiscal Year End Date]) = 2017 then [Total Compensation ($)] end), 
           [2018] = Avg(case when year([Fiscal Year End Date]) = 2018 then [Total Compensation ($)] end)
    FROM dbo.MDexec e
    Where [Fiscal Year End Date] >= '2015-01-01' 
      and [Fiscal Year End Date] < '2019-01-01'
    

    【讨论】:

    • 只要我将 0 替换为 null 就可以了。谢谢,这个解决方案更容易理解。
    • @gattoun - 我的错……更新了我们不需要 else 部分
    猜你喜欢
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2023-04-08
    • 1970-01-01
    相关资源
    最近更新 更多