SQL:选择具有列值的行n次出现并插入具有该值的行

时间:2015-10-28 14:10:47

标签: mysql sql-server python-2.7

假设我有一张桌子"员工"有两列:" id"和"名称"

id     | name    
---------+-------  
   3     | Clinton
   5     | Gates
   3     | Bush
   7     | Clinton
   7     | Obama

我想插入带有id的行(在employee表中出现2次)和任何名称。

实际上我想编写一个python脚本来让id在表中出现n次(2行表),并在该表中插入更多行,其中第一列中的ID和其他列中的硬编码名称。

for ex:能表的输出应为

id     | name    
---------+-------  
   3     | Clinton
   5     | Gates
   3     | Bush
   7     | Clinton
   7     | Obama
   3     | john
   7     | tom

2 个答案:

答案 0 :(得分:0)

尽管问题中缺少信息,但这个查询是SQL Server的一个良好开端:

declare @table table(id int, name varchar(50));
Insert into @table(id, name) values
(3, 'Clinton')
, (5, 'Gates')
, (3, 'Bush')
, (7, 'Clinton')
, (7, 'Obama');

With names(name, id) as (
    Select name, ROW_NUMBER() over(order by nid) From (
        Select distinct name, nid =  NEWID() From @table
    ) as n
)
Select ids.id, n.name From (
    Select t.id, n = ROW_NUMBER() over(order by (select 1))
    From @table t
    Inner Join (Select name From @table Group By name Having COUNT(*) > 1) d on d.name = t.name
) as ids
Inner Join names n on n.id = ids.n;

由于我不知道随机名称的来源,我重用了主名称表。 CTE随机地将名称从1到5排序。然后使用此值与重复项连接并提供ramdom输出,例如:

id  name
7   Bush
3   Obama

答案 1 :(得分:0)

使用HAVING

declare @temp table
(id  int, name nvarchar(33))

insert into @temp values (3,'Clinton')
insert into @temp values (5,'Gates  ')
insert into @temp values (3,'Bush   ')
insert into @temp values (7,'Clinton')
insert into @temp values (7,'Obama  ')

Way1:您可以使用XYZ

之类的常量字符串
insert into @temp
select id,'XYZ' from @temp 
group by id
having COUNT(id) = 2

select * from @temp

Way2:您可以使用NEWID()

生成随机字符串
insert into @temp
select id, CONVERT(varchar(255), NEWID()) from @temp 
group by id
having COUNT(id) = 2

select * from @temp