简体   繁体   English

根据字段1中的唯一值在SQL表中多次插入同一行

[英]Insert same row multiple times within SQL table based on unique value in field 1

I currently have a table where column 1 is a unique identifier for the remaining columns and I need to insert a new value into the table for each unique identifier. 我目前有一个表,其中第1列是其余列的唯一标识符,我需要为每个唯一标识符在表中插入一个新值。 The example is as follows: 示例如下:

Column 1   Column 2   Column 3 
10         Address    True 
10         City       False
10         State      True
20         Address    True
20         City       True
20         State      True

I need to insert a new row based upon each unique identifier in Column 1, like so: 我需要根据第1列中的每个唯一标识符插入新行,如下所示:

Column 1   Column 2   Column 3
10         Address    True
10         City       False
10         State      True
*10         NEW        NEW*
20         Address    True
20         City       True
20         State      True
*20         NEW        NEW*

For some reason, the SQL script for the quick lookup and insert is just escaping me on a Monday morning. 由于某种原因,用于快速查找和插入的SQL脚本只是在星期一的一个星期一逃离我。 Any help would be appreciated. 任何帮助,将不胜感激。

Thanks! 谢谢!

insert into table-name
(Column1, Column2, Column3)
select Column1, 'NEW', 'NEW*' from table-name group by Column1

You can alternatively use a distinct in the sub-select, but I have started switching to group by, which can be more flexible if I want to change a query to count or something. 您也可以在子选择中使用非重复,但是我已经开始切换为分组依据,如果我想更改查询以进行计数或其他操作,可以更加灵活。

You can try at variant of Marlin Pierce's suggestion of: 您可以尝试Marlin Pierce的以下建议:

INSERT INTO [table-name]
([Column 1], [Column 2], [Column 3])
SELECT [Column 1], 'NEW', 'NEW*' from [table-name] where [Column 2] = 'Address' group by [Column 1];

This creates a single new row for each of your existing rows. 这将为您的每个现有行创建一个新行。

See the SqlFiddle for executable sample. 有关可执行示例,请参见SqlFiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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