日期:2014-05-18  浏览次数:20459 次

各位帮忙解答这句语句
tableC

Id state flag createtime updatetime1 deletetime updatetime3  
1 创建 无 2011-07-07 无 无 无
1 删除 无 无 无 2011-08-07 无
1 更新 1 无 2011-08-13 无 无  
1 更新 3 无 无 无 2011-08-08  
3 创建 无 2011-07-07 无 无 无
3 删除 无 无 无 2011-08-07 无

   
我想实现这样一个效果,只要Id=1的情况


Id state dealtime(处理时间)
1 创建 2011-07-07
1 删除 2011-08-07
1 更新 2011-08-13
1 更新 2011-08-08  




请问这样一句case when语句应该怎么写?
或者有比case when语句更方便的方法?

------解决方案--------------------
SQL code
create table tb(Id int,state nvarchar(10),flag nvarchar(10),createtime datetime,updatetime1 datetime,deletetime datetime,updatetime3 datetime)  
insert into tb select 1,'创建','无','2011-07-07','2011-03-03','2011-03-04','2011-03-05'
insert into tb select 1,'删除','无','2011-03-06','2011-03-07','2011-08-07','2011-04-02'
insert into tb select 1,'更新','1','2011-04-03','2011-08-13','2011-04-04','2011-04-07'
insert into tb select 1,'更新','3','2011-04-08','2011-04-10','2011-04-11','2011-08-08'  
insert into tb select 3,'创建','无','2011-07-07','2011-03-03','2011-03-04','2011-03-05'
insert into tb select 3,'删除','无','2011-03-06','2011-03-07','2011-08-07','2011-04-02'
go
select id,state,
(case when state='创建' then createtime when state='删除' then deletetime when state='更新' and flag=1 then updatetime1 when state='更新' and flag=3 then updatetime3 end) as dealtime
from tb
where id=1
/*
id          state      dealtime
----------- ---------- -----------------------
1           创建         2011-07-07 00:00:00.000
1           删除         2011-08-07 00:00:00.000
1           更新         2011-08-13 00:00:00.000
1           更新         2011-08-08 00:00:00.000

(4 行受影响)

*/
go
drop table tb