简体   繁体   English

如何为列中找到的每个唯一值插入行

[英]How to insert row for each unique value found in column

How could I, in SQL Server 2008, write a SQL statement that would insert one row for each distinct value it finds in one column in the same table? 如何在SQL Server 2008中编写一条SQL语句,为在同一表的一列中找到的每个不同的值插入一行?

Edit: 编辑:
The table I want to add rows to the same table I'm checking. 我想向正在检查的同一张表中添加行的表。

I have normalized table with a column [Name], and [Hobby], so how do I insert one new hobby for each name? 我已经标准化了带有[名称]和[爱好]列的表格,那么如何为每个名称插入一个新的爱好?

Input greatly appreciated =] 输入非常感谢=]

try 尝试

INSERT INTO TargetTable (SomeColumn)
SELECT DISTINCT TheSourceColumn From SomeSourceTable;

IF that is not what you are looking for please provide more details like what the data model looks like etc. 如果不是您要查找的内容,请提供更多详细信息,例如数据模型的外观等。

UPDATE - after edit from OP: 更新-从OP编辑后:

I am not sure that you data model is good but you can do this: 我不确定您的数据模型是否良好,但是您可以这样做:

INSERT INTO TheTable (NAME, HOBBY)
SELECT DISTINCT X.NAME, @SomeHOBBY FROM TheTable X;

You could use something like 您可以使用类似

Insert into table1
Select distinct col1 from tabl2

The above should work as long as table1 has just one column of the same data type as col1 of tabl2 只要table1仅具有与tabl2的col1相同数据类型的一列,以上方法就可以工作

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

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