将查询结果保存到多个SQL表中并在这些表之间进行连接(SQL Server)

时间:2015-02-17 22:36:48

标签: sql sql-server

我需要将多个查询结果保存到SQL表中,以便我可以在这些查询结果/ SQL表之间进行连接以进行进一步分析。

首先查询:

with CTE as 
(
   select year, origin, (acX + commX + intX) as totalX,
   RN = ROW_NUMBER() OVER (PARTITION BY origin ORDER BY origin,year)
   from tableX
)
SELECT a.year, a.origin, a.totalX, b.totalX as totalX_lag,
  (a.totalX-b.totalX)/a.totalX as growthX
FROM  CTE as a                      
      JOIN CTE as b     
        ON a.origin = b.origin AND a.RN = b.RN + 1  

第二次查询:

with CTE2 as 
(
    select year, origin, (acY +commY+ intY) as totalY,
      RN = ROW_NUMBER() OVER (PARTITION BY origin ORDER BY origin,year)
    from tableY
)
SELECT a.year, a.origin, a.totalY, b.totalY as totalY_lag,
    (a.totalY-b.totalY)/a.totalY as growthY
FROM  CTE2 as a                     
    JOIN CTE2 as b      
    ON a.origin = b.origin AND a.RN  = b.RN + 1  

我需要将第一个查询的结果保存为A,将第二个查询结果保存为B,然后执行以下操作:

select *
from A
join B on A.origin=B.origin and A.year=B.year

我该如何做到这一点?

1 个答案:

答案 0 :(得分:3)

你可以SELECT * INTO #TemporalTable。例如:

WITH CTE1 AS
(
   SELECT ..
   FROM ..
   WHERE
)
SELECT * INTO #CTE1 
FROM 
    CT1 JOIN WhatEver ON ..
WHERE ...

WITH CTE2 AS
(
   SELECT ..
   FROM ..
   WHERE
)
SELECT * INTO #CTE2 
FROM 
   CTE2 JOIN WhateEver2 
      ON ...
WHERE ...

SELECT ...
FROM 
  #CTE1 JOIN #CTE2 ON ..
WHERE
  ...

但可能你不需要时态表。你可以链接CTE;

WITH CTE1 AS
(
   SELECT ..
   FROM ..
   WHERE
)    
, CTE2 AS
(
   SELECT ..
   FROM CTE1 JOIN WhatEver ON .. 
   WHERE ..
)
, CTE3 AS
(
   SELECT ..
   FROM CTE2 JOIN WhateEver ON ..
   WHERE ..
)    
SELECT ...
FROM 
  CTE3 JOIN WhatEver ON ..
WHERE
  ...