2016-04-17 18 views
-1

最初の最小レコードと2番目の最小値を取得する必要があるため、テーブル1とテーブル2を2回結合したいとします。しかし、私は2番目の最小レコードを取得するためにcteを使うことしか考えていません。それを行うより良い方法はありますか?ここでSQL MinとSec Minの行を持つテーブルを結合する

は、テーブルのテーブルです:

私は、その出力値が出力値Iが使用しています0

enter image description here

現在のコードである1と第2 RUNIDで出力テーブルFirstRunIDでメンバーに参加したいです:

select memid, a.runid as aRunid,b.runid as bRunid 
into #temp 
from FirstTable m inner join 
(select min(RunID), MemID [SecondTable] where ouput=1 group by memid)a on m.memid=a.memid 
inner join (select RunID, MemID [SecondTable] where ouput=0)b on m.memid=a.memid and b.runid>a.runid 

with cte as 
(
select row_number() over(partition by memid, arunid order by brunid),* from #temp 
) 

select * from cte where n=1 
+0

ご希望の出力は、私には意味がありません。 'Memid = 2'の場合、' output = 1' **の最初の 'RunID'は** ** **ではなく1 **です。これは単なる例であり、他にもあります。あなたの構造とデータのSQLフィドルを追加して、適切に再吟味するか、目的の出力を修正してください。 –

+0

ありがとうございます。私は欲望の出力を修正しました。 – keivn

答えて

0

あなたはこのためにouter apply演算子を使用することができます。

select * from t1 
outer apply(select top 1 t2.runid from t2 
      where t1.memid = t2.memid and t2.output = 1 order by t2.runid) as oa1 
outer apply(select top 1 t2.runid from t2 
      where t1.memid = t2.memid and t2.output = 0 order by t2.runid) as oa2 
0

これは、条件付き集計で行うことができます。あなたの結果をもとに、あなたは最初のテーブルを必要としません:

select t2.memid, 
     max(case when output = 1 and seqnum = 1 then runid end) as OutputValue1, 
     max(case when output = 0 and seqnum = 2 then runid end) as OutputValue2 
from (select t2.*, 
      row_number() over (partition by memid, output order by runid) a seqnum 
     from t2 
    ) t2 
group by t2.memid; 
0
declare @FirstTable table 
(memid int, name varchar(20)) 
insert into @firsttable 
values 
(1,'John'), 
(2,'Victor') 

declare @secondtable table 
(runid int,memid int,output int) 

insert into @secondtable 
values 
(1,1,0),(1,2,1),(2,1,1),(2,2,1),(3,1,1),(3,2,0),(4,1,0),(4,2,0) 

;with cte as 
(
SELECT *, row_number() over (partition by memid order by runid) seq  --sequence 
FROM @SECONDTABLE T 
where t.output = 1 
union all 
SELECT *, row_number() over (partition by memid order by runid) seq  --sequence 
FROM @SECONDTABLE T 
where t.output = 0 and 
t.runid > (select min(x.runid) from @secondtable x where x.memid = t.memid and x.output = 1 group by x.memid) --lose any O output record where there is no prior 1 output record 
) 
select cte1.memid,cte1.runid,cte2.runid from cte cte1 
join cte cte2 on cte2.memid = cte1.memid and cte2.seq = cte1.seq 
where cte1.seq = 1             --remove this test if you want matched pairs 
     and cte1.output = 1 and cte2.output = 0 
関連する問題