日期:2014-05-19  浏览次数:20584 次

求一条SQL语句,在线等待。请大家帮忙!
我有一个表,记录用户发起流程的状态信息。每个客户可发起多次两种类型的流程:
分别为:流程1,流程2。这个表的结构如下:
(用户ID,流程1ID,流程1状态,   流程2ID,流程2状态)

每次启动流程,会产生一条记录(流程的ID号递增方式产生)。如果启动流程1,系统会产生一个流程1的ID,记录该流程的处理状态(状态有:开始,处理中,取消,完成),而流程2ID的相关信息为空。如果启动流程2,则又另外产生一条记录,记录流程2的信息,流程1的信息
在该记录中都为空。

我现在想查询用户启动的最近的流程1和最近的流程2的状态,查询结果如下:
用户ID,   流程1状态,流程2状态

一条SQL语句不知道能不能查询出来?谢谢!

------解决方案--------------------
select a.用户ID,a.流程1状态,b.流程2状态
from (select 用户ID,流程1状态 from table where 流程1ID=max(流程1ID) and 流程1状态 <> ' ' and 用户ID=ID_NO) a,
(select 用户ID,流程2状态 from table where 流程2ID=max(流程2ID) and 流程2状态 <> ' ' and 用户ID=id_no) b

------解决方案--------------------
drop table tbtest
go
create table tbtest(用户ID varchar(20),流程1ID varchar(20),流程1状态 varchar(20),流程2ID varchar(20),流程2状态 varchar(20))
insert into tbtest
select '001 ', '001 ', '取消 ',NULL,NULL
union all select '001 ',NULL,NULL, '002 ', '处理中 '
union all select '001 ', '003 ', '处理中 ',NULL,NULL
union all select '002 ', '004 ', '开始 ',NULL,NULL

select tbtest.用户ID,
(select 流程1状态 from tbtest a where a.流程1ID=t.流程1ID) as '流程1状态 ',
(select 流程2状态 from tbtest b where b.流程2ID=tt.流程2ID) as '流程2状态 '
from (select distinct 用户ID from tbtest)tbtest
inner join (select 用户ID,max(流程1ID) as '流程1ID ' from tbtest group by 用户ID)t on tbtest.用户ID=t.用户ID
inner join (select 用户ID,max(流程2ID) as '流程2ID ' from tbtest group by 用户ID)tt on tbtest.用户ID=tt.用户ID

/*
用户ID 流程1状态 流程2状态
-------------------- -------------------- --------------------
001 处理中 处理中
002 开始 NULL

(所影响的行数为 2 行)
*/
------解决方案--------------------
学习ing!
------解决方案--------------------
if object_id( 'pubs..tb ') is not null
drop table tb
go

create table tb(用户ID varchar(10),流程1ID varchar(10),流程1状态 varchar(10),流程2ID varchar(10),流程2状态 varchar(10))
insert into tb(用户ID,流程1ID,流程1状态,流程2ID,流程2状态) values( '001 ', '001 ', '取消 ' , ' ' , ' ' )
insert into tb(用户ID,流程1ID,流程1状态,流程2ID,流程2状态) values( '001 ', ' ' , ' ' , '002 ', '处理中 ')
insert into tb(用户ID,流程1ID,流程1状态,流程2ID,流程2状态) values( '001 ', '003 ', '处理中 ', ' ' , ' ' )
insert into tb(用户ID,流程1ID,流程1状态,流程2ID,流程2状态) values( '002 ', '004 ', '开始 ' , ' ' , ' ' )
go

select m.* , n.流程2状态 from
(
select a.用户ID,a.流程1状态 from tb a,
(select 用户ID , max(流程1ID) 流程1ID from tb group by 用户ID) b
where a.用户ID = b.用户ID and a.流程1ID = b.流程1ID
) m,
(
select a.用户ID,a.流程2状态 from tb a,
(select 用户ID , max(流程2ID) 流程2ID from tb group by 用户ID) b
where a.用户ID = b.用户ID and a.流程2ID = b.流程2ID
) n
where m.用户ID = n.用户ID
drop table tb

/*
用户ID 流程1状态 流程2状态
---------- ---------- ----------
001 处理中 处理中
002 开始

(所影响的行数为 2 行)
*/