日期:2014-05-17  浏览次数:20448 次

这个MSSQL语句怎么写(groupby)
  table1
id  name  statu
2   aaa   已完成
16  bbb   已完成 
32  aaa   进行中
46  ggg   已完成  
416 bbb   已完成 

 table2
 id name count finishTime

想要把table1中,当同一个name的statu的全部为已完成时,把所有的name删除并插入到table2(table2插入时显示完成的个数)中,即是运行后两个表变成下面,请问SQL如何写啊。。谢谢

 table1
id  name  statu
2   aaa   已完成
32  aaa   进行中
 
 table2
 id name count finishTime
 1  bbb  2     getdate()
 2  ggg  1     getdate()

------解决方案--------------------
create table table1(id int, name varchar(10), statu varchar(20))

insert into table1
select 2   ,'aaa'   ,'已完成' union all
select 16  ,'bbb'   ,'已完成' union all 
select 32  ,'aaa'   ,'进行中' union all
select 46  ,'ggg'   ,'已完成' union all
select 416 ,'bbb'   ,'已完成' 
go


create table table2(id int identity(1,1), name varchar(10), count int, finishTime datetime)
go


insert into table2(name,count,finishTime)
select name,COUNT(*),GETDATE()
from table1
group by name
having COUNT(case when statu = '已完成' then 1 else null end) = COUNT(*)


delete table1
where name in (select name from table1 group by name
               having COUNT(case when statu = '已完成' then 1 else null end) = COUNT(*))
               

select * from table1
/*
id name statu
2 aaa 已完成
32 aaa 进行中
*/

select * from table2  
/*
id name count finishTime
1 bbb 2 2013-12-25 09:22:03.137
2 ggg 1 2013-12-25 09:22:03.137
*/            

------解决方案--------------------

SELECT *
FROM [table1] a
WHERE name IN (SELECT name FROM table1 WHERE stat