我有一个SQL Server表和一个查询,它会产生一个带有两个数据透视列的数据透视表。以前它只使用一个枢轴列(pvt1)。
SELECT
MIN([Created Date]),
MIN([2]) AS [2],
MIN([4]) AS [4],
MIN([12]) AS [12],
MIN([18]) AS [18],
MIN([47]) AS [47],
MIN([88]) AS [88],
MIN([982]) AS [982],
MIN([1033]) AS [1033],
MIN([2360]) AS [2360],
MIN([3759]) AS [3759],
MIN([3974]) AS [3974],
MIN([5586]) AS [5586]
FROM
(SELECT
year(udp.CreatedDate) AS "Created Date",
MAX(udp.Participant) AS "Participant",
MAX(udp.LastModifiedDate) AS "Last Modified Date",
MAX(udp.Client) AS "Client"
FROM
UDP_Table AS udp
WHERE
1=1
GROUP BY
year(udp.CreatedDate)) AS source
PIVOT (
MAX([Last Modified Date])
FOR
[Participant] IN ([2], [4], [12], [18], [47], [88])
)
as pvt1
PIVOT (
MAX([Last Modified Date])
FOR
[Client] IN ([982], [1033], [2360], [3759], [3974], [5586])
)
as pvt2
GROUP BY
[Created Date]
ORDER BY
[Created Date] asc
结果是:
[S0001] [207]无效的列名称“上次修改日期”。
奇怪的是当我尝试这个示例表和查询(参见下面的链接)时,它具有与我相同的结构,它可以工作。
http://pratchev.blogspot.de/2009/01/pivoting-on-multiple-columns.html
我的查询有什么问题?
答案 0 :(得分:0)
您的第一个数据透视表将列[Last Modified Date]
转换为名为[2], [4], [12], [18], [47], [88]
的列,因此[Last Modified Date]
不存在第二个数据透视表。您发布的示例为每个分支SUM(value) AS value
和SUM(quantity) AS quantity
我不是100%确定您要完成的任务,但根据您的最终SELECT,您需要为每个参与者和每个客户创建一个列。你应该做一个UNION来加入记录,然后只做1个Pivot。
这看起来像这样。
SELECT *
FROM
(SELECT
year(udp.CreatedDate) AS "Created Date",
MAX(udp.Participant) AS "Participant",
MAX(udp.LastModifiedDate) AS "Last Modified Date",
FROM
UDP_Table AS udp
GROUP BY
year(udp.CreatedDate)
UNION ALL
SELECT
year(udp.CreatedDate) AS "Created Date",
MAX(udp.Client) AS "Participant",
MAX(udp.LastModifiedDate) AS "Last Modified Date",
FROM
UDP_Table AS udp
GROUP BY
year(udp.CreatedDate)
) AS source
PIVOT (
MAX([Last Modified Date])
FOR [Participant] IN ([2], [4], [12], [18], [47], [88], [982], [1033], [2360], [3759], [3974], [5586])
)
as pvt1