2
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

如何将行插入到 T1 中的表 T2 中,与 C1 列匹配,其中列的值来自 T2 中按 C1 排序的先前行?

如果没有先前的值,即C1=9,则不应插入新行。

4

3 回答 3

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。

于 2013-05-23T18:47:39.627 回答
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上的演示

于 2013-05-23T21:15:58.783 回答
-2
create table t2 
as 
select * from t1

还有另一个机会

UNION and UNION ALL

...

select distinct * from t2
于 2013-05-23T18:41:45.040 回答