使用多个WITH tablename AS(...)语句SQL Server

时间:2017-12-06 17:54:45

标签: sql sql-server sql-server-2008

我试图创建两个临时表并使用永久表连接它们。例如:

WITH temp1 AS (COUNT(*) AS count_sales, ID FROM table1 GROUP BY ID)
WITH temp2 AS (COUNT(*) AS count_somethingelse, ID FROM table2 GROUP BY ID)
SELECT *
FROM table3 JOIN table2 JOIN table1
     ON table1.ID = table2.ID = table3.ID

但似乎存在多个WITH tablename AS(...)语句的问题。我试了一个分号。

2 个答案:

答案 0 :(得分:4)

您的查询应该更像这样:

WITH temp1 AS (
      SELECT COUNT(*) AS count_sales, ID
      FROM table1
      GROUP BY ID
     ),
     temp2 AS (
      SELECT COUNT(*) AS count_somethingelse, ID
      FROM table2
      GROUP BY ID
     )
SELECT *
FROM temp2 JOIN 
     temp1
     ON temp1.ID = temp2.ID;

您的查询有多个错误。我建议你首先要了解这个版本的工作原理 - 或者至少做某些而不是报告语法错误。然后,再回过头来学习SQL。

答案 1 :(得分:0)

  

我正在尝试创建两个临时表

为了清楚起见......你使用的CTE与临时表不完全相同。你还标记了'临时表',所以你想要一个临时表?您可以将查询结果存储在声明的表变量或实际的临时表中。

声明的表变量的示例:

DECLARE @table1 TABLE(id int, count_sales int) 

INSERT INTO @table1 (id, count_sales)
SELECT ID, COUNT(*)
  FROM table1
GROUP BY ID
--or however you populate temp table1

DECLARE @table2 TABLE(id int, count_somethingelse int)

INSERT INTO @table2 (id, count_somethingelse)
SELECT ID, COUNT(*)
  FROM table2
GROUP BY ID
--or however you populate temp table2

SELECT T3.id
      --,T2.(some column)
      --,T1.(some column)
      --,etc...
FROM table3 T3 INNER JOIN @table2 T2 ON T3.id = T2.id
               INNER JOIN @table1 T1 ON T3.id = T1.id
相关问题