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 statu!='已完成')
INSERT INTO table2(name,statu,[count])
SELECT name,statu,COUNT(name)[count],GETDATE()
FROM TABLE1
WHERE name NOT IN (SELECT name FROM table1 WHERE statu!='已完成')
GROUP BY name,statu
------解决方案--------------------
插入我就不写了
----------------------------------------------------------------
-- Author :DBA_Huangzj(發糞塗牆)
-- Date :2013-12-25 09:20:22
-- Version:
-- Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
-- Dec 28 2012 20:23:12
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )
--
----------------------------------------------------------------
--> 测试数据:[table1]
if object_id('[table1]') is not null drop table [table1]
go
create table [table1]([id] int,[name] varchar(3),[statu] varchar(6))
insert [table1]
select 2,'aaa','已完成' union all
select 16,'bbb','已完成' union all
select 32,'aaa','进行中' union all
select 46,'ggg','已完成' union all
select 416,'bbb','已完成'
--------------开始查询--------------------------
SELECT *
FROM [table1] a
WHERE name IN (SELECT name FROM table1 WHERE statu!='已完成')
--INSERT INTO table2(name,statu,[count])
SELECT name,statu,COUNT(name)[count],GETDATE()
FROM TABLE1
WHERE name NOT IN (SELECT name FROM table1 WHERE statu!='已完成')
GROUP BY name,statu
----------------结果----------------------------