这个问题是基于我之前的问题
SQL server 2008 R2, select one value of a column for each distinct value of another column
关于SQL Server 2008上的CTE。
WITH my_cte(id_num, rn) AS (
SELECT name,
rn = ROW_NUMBER() OVER (PARTITION BY a.name ORDER BY newid())
FROM my_table as a
)
SELECT id_num FROM my_cte WHERE rn = 1
INSERT INTO #temp_table
SELECT a.address from another_table as a,
id_num from my_cte -- here, I got error!!!
为什么我收到错误:关键字'来自'。
附近的语法不正确我需要一个新表,其中包含来自another_table的一列和来自my_cte的一列。
e.g。
address (from another_table) id_num (from my_cte)
city_1 65
city_1 36
city_2 65
city_2 36
city_3 65
city_3 36
我应该使用哪种连接来获取上表,以便每个地址都与CTE中的所有id_num相关联?假设id_num只有65和36两个值。 my_cte没有地址栏。
任何帮助都将不胜感激。
答案 0 :(得分:2)
CTE只能在其后面的语句中使用。执行SELECT id_num FROM my_cte WHERE rn = 1
后,cte不再存在。
答案 1 :(得分:1)
CTE仅存在于单个查询中。但您可以将其与insert
以及select
:
WITH my_cte(id_num, rn) AS (
SELECT name, ROW_NUMBER() OVER (PARTITION BY a.name ORDER BY newid()) as rn
FROM my_table as a
)
INSERT INTO #temp_table
SELECT a.address, id_num
from another_table as a JOIN
my_cte
on a.name = my_cte.name;