如何将来自2个单独临时表的输出合并为单个查询?

时间:2018-01-28 08:24:35

标签: sql sql-server tsql union temp-tables

我正在使用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个透视结果合并为一个单独的输出表。但是,这不起作用!如何重新编写此查询?

1 个答案:

答案 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;

那就是说,我不认为你的查询有效。此答案仅解决有关将数据保存到一个表的语法问题。