これは私の意見では少なくとも一つの他の上にいくつかのサブクエリよりも読みやすく、理解し少し簡単で、派生テーブルといくつかのウィンドウ関数を用いて達成することができる。
declare @Approval table(RequestNo nvarchar(10),UserName nvarchar(10),Action nvarchar(10),Seq int,ActionDate date);
insert into @Approval values ('R001','JohnD','Requestor',1,'20170101'),('R001','SamS','Verifier',2,NULL),('R001','TrishL','Verifier',3,'20170102'),('R001','GeorgeP','Verifier',4,NULL),('R001','JackF','Approver',5,NULL),('R001','RobertL','Approver',6,NULL);
with c as
(
select RequestNo
,min(Seq) as MinSeq
,max(Seq) as MaxSeq
,row_number() over (partition by RequestNo order by RequestNo, min(ActionDate), min(Seq)) as rn
from @Approval
group by RequestNo
,Action
)
select a.*
from @Approval a
join c
on(a.RequestNo = c.RequestNo
and a.Seq between c.MinSeq and c.MaxSeq
and c.rn = 1
)
order by a.RequestNo
,a.Seq;
出力:追加のDATに追加
+-----------+----------+----------+-----+------------+
| RequestNo | UserName | Action | Seq | ActionDate |
+-----------+----------+----------+-----+------------+
| R001 | JackF | Approver | 5 | NULL |
| R001 | RobertL | Approver | 6 | NULL |
+-----------+----------+----------+-----+------------+
それはセット全体にどのように動作するかを示すために:
declare @Approval table(RequestNo nvarchar(10),UserName nvarchar(10),Action nvarchar(10),Seq int,ActionDate date);
insert into @Approval values
('R001','JohnD','Requestor',1,'20170101'),('R001','SamS','Verifier',2,NULL),('R001','TrishL','Verifier',3,'20170102'),('R001','GeorgeP','Verifier',4,NULL),('R001','JackF','Approver',5,NULL),('R001','RobertL','Approver',6,NULL)
,('R002','JohnD','Requestor',1,'20170101'),('R002','SamS','Verifier',2,NULL),('R002','TrishL','Verifier',3,null),('R002','GeorgeP','Verifier',4,NULL),('R002','JackF','Approver',5,NULL),('R002','RobertL','Approver',6,NULL);
出力:
+-----------+----------+----------+-----+------------+
| RequestNo | UserName | Action | Seq | ActionDate |
+-----------+----------+----------+-----+------------+
| R001 | JackF | Approver | 5 | NULL |
| R001 | RobertL | Approver | 6 | NULL |
| R002 | SamS | Verifier | 2 | NULL |
| R002 | TrishL | Verifier | 3 | NULL |
| R002 | GeorgeP | Verifier | 4 | NULL |
+-----------+----------+----------+-----+------------+
はあなたのクエリは、これまでのように何を求めず、あなたはどのようなエラーを取得していますか? –
入力データと予想される出力は何ですか? –