我有一个包含500行的表,另一个包含750行左右的表。我正在做的是,我从第二个表中获取了某一列的随机500行,并且我希望使用这500个值更新第一个表上新添加的列。
我知道如何进行如下更新:
UPDATE schema.table1
SET column = cl.column FROM schema.table1 cl
INNER JOIN table2 cf ON cf.column = cl.column
但我没有在两个表中都匹配的任何列。有没有办法在不必匹配内部联接的列的情况下执行此操作?
基本上,我想在一个表中更新500行1列,其中500个值来自另一个表
答案 0 :(得分:1)
您可以使用ROW_NUMBER
生成列来连接两个表。看一下示例和输出
DECLARE @T1 TABLE ( column1 INT ,column2 VARCHAR(2) )
DECLARE @T2 TABLE ( column1 VARCHAR(2) )
INSERT INTO @T1 ( column1, column2 )
VALUES ( 0, 'A' ), ( 1, 'B' ), ( 2, 'C' )
INSERT INTO @T2 ( column1 )
VALUES ( 'D'),( 'F'),( 'G' )
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T1
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T2
;WITH CTE_1 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T1)
,cte_2 AS (SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T2)
UPDATE t1
SET t1.column2 = t2.column1
FROM CTE_1 t1
JOIN cte_2 t2
ON t1.rn = t2.rn
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T1
SELECT *, ROW_NUMBER() OVER (PARTITION BY 1 ORDER BY (SELECT NULL) ) AS RN FROM @T2