我正在尝试在兼容级别80上运行的SQL Server 2008 SP3数据库上使用UNPIVOT提取数据。这应该意味着UNPIVOT无法正常工作,但在某些情况下,它确实可以正常工作...
作品:
形式的独立SELECT查询:
SELECT...FROM...UNPIVOT...WHERE...GROUP BY
不起作用:
同一查询,位于LEFT JOIN ()
同一服务器内不同数据库的其他表上。全部处于兼容级别80。
我收到通常的错误消息:
Msg 325, Level 15, State 1, Line 165
Incorrect syntax near 'UNPIVOT'. You may need to set the compatibility level
of the current database to a higher value to enable this feature. See help for
the SET COMPATIBILITY_LEVEL option of ALTER DATABASE.
UNPIVOT
解决方法似乎很麻烦,如果可能的话,我希望此查询是独立的且可刷新的。如果可以让查询独立运行,这似乎是合乎逻辑的,那么应该可以在中使用它JOIN
。
问题:
为什么有时会起作用?
在这种情况下,如何在中实现UNPIVOT
子查询JOIN
?
取消子查询:(按要求...)
SELECT
YEAR(CAST('1-'+UnPiv.[Date] AS DATE)) "Year",
MONTH(CAST('1-'+UnPiv.[Date] AS DATE)) "Month",
CASE [Channel_Org]
WHEN 'TPR' THEN 'ERP'
ELSE [Channel_Org]
END AS [Channel_Org],
ISNULL(SUM(CASE WHEN [GL Desc] = 'EIP' AND
[OPEX_Group] = 'Postpaid SAC' THEN [Amount] END),0) "Post EIP",
ISNULL(SUM(CASE WHEN [GL Desc] = 'EIP' AND
[OPEX_Group] = 'Prepaid SAC' THEN [Amount] END),0) "Pre EIP",
ISNULL(SUM(CASE WHEN [GL Desc] = 'EIP' AND
[OPEX_Group] = 'SRC' THEN [Amount] END),0) "Upg EIP",
ISNULL(SUM(CASE WHEN [GL Desc] = 'MDF (OEM)' AND
[OPEX_Group] = 'Postpaid SAC' THEN [Amount] END),0) "Post MDF",
ISNULL(SUM(CASE WHEN [GL Desc] = 'MDF (OEM)' AND
[OPEX_Group] = 'Prepaid SAC' THEN [Amount] END),0) "Pre MDF",
ISNULL(SUM(CASE WHEN [GL Desc] = 'MDF (OEM)' AND
[OPEX_Group] = 'SRC' THEN [Amount] END),0) "Upg MDF"
FROM [Channel_Steering].[dbo].[AQ1_OPEX_View]
UNPIVOT (Amount FOR [Date] 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])) UnPiv
WHERE ( [Channel_Org] IN ('Retail','TPR')
AND
[GL Desc] IN ('MDF (OEM)', 'EIP')
)
GROUP BY
[Channel_Org],
YEAR(CAST('1-'+UnPiv.[Date] AS DATE)),
MONTH(CAST('1-'+UnPiv.[Date] AS DATE))