我正在使用SQL Server 2012
,我有2个单独的T-SQL
个查询,我尝试合并为一个查询。
查询1:
USE MyDatabase
SELECT [Col A], [Col B], [Col C]
INTO #TempTable
FROM MyList
WHERE [Date] >= '2018-01-01'
SELECT * FROM #TempTable
PIVOT(SUM([Col B])
FOR [Col A] IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable
查询2:
USE MyDatabase
SELECT [Col A], [Col B], [Col C]
INTO #TempTable2
FROM MyList
WHERE [StayDate] >= '2018-01-01'
AND [DateCreated] <= '2018-01-27'
SELECT * FROM #TempTable2
PIVOT(SUM([Col B])
FOR [Col A] IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable
我尝试使用UNION ALL
语法,如下所示:
USE MyDatabase
SELECT [Col A], [Col B], [Col C]
INTO #TempTable
FROM MyList
WHERE [StayDate] >= '2018-01-01'
PIVOT(SUM([Col B])
FOR [Col A] IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable
UNION ALL
SELECT [Col A], [Col B], [Col C]
INTO #TempTable2
FROM MyList
WHERE [StayDate] >= '2018-01-01'
AND [DateCreated] <= '2018-01-27'
PIVOT(SUM([Col B])
FOR [Col A] IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable
我的目标是将2个透视结果合并为一个单独的输出表。但是,这不起作用!如何重新编写此查询?
答案 0 :(得分:0)
如果您想在一个表中使用此功能,则查询中只有一个into
。对于UNION ALL
,这是在第一个查询中:
SELECT [Col A], [Col B], [Col C]
INTO #TempTable
FROM MyList
WHERE [StayDate] >= '2018-01-01'
PIVOT(SUM([Col B])
FOR [Col A] IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable
UNION ALL
SELECT [Col A], [Col B], [Col C]
FROM MyList
WHERE [StayDate] >= '2018-01-01'
AND [DateCreated] <= '2018-01-27'
PIVOT(SUM([Col B])
FOR [Col A] IN ([Jan], [Feb], [Mar], [Apr], [May], [Jun], [Jul], [Aug], [Sep], [Oct], [Nov], [Dec])) AS PVTTable;
那就是说,我不认为你的查询有效。此答案仅解决有关将数据保存到一个表的语法问题。