CREATE TABLE T1 (C1 INT);
CREATE TABLE T2 (C1 INT, C2 INT);
INSERT INTO T1 VALUES (9), (10), (12), (13), (21), (53), (111);
INSERT INTO T2 VALUES (10, 3), (12, 6), (21, 9);
Desired values in T2
C1 C2
10 3
12 6
13 6 -- duplicate value from row C1=12
21 9
53 9 -- duplicate value from row C1=21
111 9 -- duplicate value from row C1=21
如何将行插入表T2, 在T1中,在C1列上匹配 列的值来自T2排序的T2中的前一行?
如果没有先前的值,即C1 = 9,则不应插入新行。
答案 0 :(得分:0)
insert into T2 (C1, C2)
select a.C1, b.C2
from T1 a
cross apply (
select top 1
C2
from T2
where T2.C1 < a.C1
order by T2.C1 desc
) b
where a.C1 not in (select C1 from T2)
您也可以使用相关子查询而不是交叉应用,但如果没有先前的C1,则需要额外检查以避免插入null。
答案 1 :(得分:0)
假设T2.C2按升序排列,可以使用带有ORDER BY子句的MAX聚合函数
;WITH cte AS
(
SELECT T1.C1 AS t1C1, T2.C1 AS t2C1,
MAX(T2.C2) OVER(ORDER BY T1.C1) AS C2
FROM T1 LEFT JOIN T2 ON T1.C1 = T2.C1
)
SELECT t1C1 AS C1, C2
FROM cte
WHERE C2 IS NOT NULL AND t2C1 IS NULL
SQLFiddle上的演示
答案 2 :(得分:-2)
create table t2
as
select * from t1
还有另一个机会
UNION and UNION ALL
...
和
select distinct * from t2