我正在使用pivot编写一个sql查询,我收到以下错误:
Msg 156, Level 15, State 1, Line 14
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near ')'.
我写的查询是:
select *
from (
select a.ID as id,
a.dataValue as value
from dbo.TableA a (nolock)
where a.ID in (select b.ID from dbo.TableB b(nolock))
and a.someOtherId = '4000'
and a.DT = '2/16/2011 12:00:00'
)as data
pivot
(
sum([value])
for [id] in (select ID from dbo.TableB (nolock))
) as pvt
任何人都可以帮我解决这个问题吗?提前致谢。
答案 0 :(得分:1)
根据Microsoft的文档,您无法在select
之后使用in
:您必须手动列出值。
[<column that contains the values that will become column headers>]
IN ( [first pivoted column], [second pivoted column],
... [last pivoted column])
) AS <alias for the pivot table>
假设select b.ID from dbo.TableB b(nolock)
返回1
,2
,3
,您可以像这样重写代码:
select *
from (
select a.ID as id,
a.dataValue as value
from dbo.TableA a (nolock)
where a.ID in (1,2,3)
and a.someOtherId = '4000'
and a.DT = '2/16/2011 12:00:00'
)as data
pivot
(
sum([value])
for [id] in ([1],[2],[3])
) as pvt
答案 1 :(得分:0)
您无法动态构建for in子句中的字段列表。
for [id] in (select ID from dbo.TableB (nolock))
这是不允许的。您必须明确列出列名称(抱歉)
更改:从dbo.TableB中选择ID 收件人:(Field1,field2,Field3) - 要返回的字段的实际名称
-- Pivot table with one row and five columns
SELECT 'AverageCost' AS Cost_Sorted_By_Production_Days,
[0], [1], [2], [3], [4]
FROM
(SELECT DaysToManufacture, StandardCost
FROM Production.Product) AS SourceTable
PIVOT
(
AVG(StandardCost)
FOR DaysToManufacture IN ([0], [1], [2], [3], [4])
) AS PivotTable;