简体   繁体   中英

Insert distinct values from one table into another table

So for each distinct value in a column of one table I want to insert that unique value into a row of another table.

list = select distinct(id) from table0

for distinct_id in list
 insert into table1 (id) values (distinct_id)
end

Any ideas as to how to go about this?

Whenever you think about doing something in a loop, step back, and think again. SQL is optimized to work with sets. You can do this using a set-based query without the need to loop:

INSERT dbo.table1(id) SELECT DISTINCT id FROM dbo.table0;

There are some edge cases where looping can make more sense, but as SQL Server matures and more functionality is added, those edge cases get narrower and narrower...

insert into table1 (id)
select distinct id from table0

以下声明适用于我。

insert into table1(col1, col2) select distinct on (col1) col1 col2 from table0 

下面的查询还将检查表 2 中的现有数据。

INSERT INTO Table2(Id) SELECT DISTINCT Id FROM Table1 WHERE Id NOT IN(SELECT Id FROM Table2);

Other Simple way to copy distinct data with multiple columns from one table to other

Insert into TBL2 
Select * from (Select COL1, ROW_NUMBER() over(PARTITION BY COL1 Order By COL1) AS COL2 From TBL1)T
where T.COL2 = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM