2017-07-31 84 views
2

,我發現了以下錯誤:SQL服務器:透視功能錯誤

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '('.

當執行此查詢:

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上的開頭括號。

回答

3

你需要一個別名分配給DATEPART表達和使用您的數據透視子句中:

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; 
+0

你打我吧。 – Eli

1

你不需要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替換0就行。謝謝,這個解決方案更容易理解。 – gattoun

+0

@gattoun - 我的不好..更新了我們不需要'else'部分 –