带有Min和Sec Min行的SQL连接表

时间:2016-04-17 09:36:59

标签: sql sql-server tsql

我希望将table1与table2连接两次,因为我需要获得第一个最小记录和第二个最小记录。但是,我只能想到使用cte来获得第二个最小记录。有没有更好的方法呢?

这是表格表格:

我想使用输出值为1的输出表FirstRunID和输出值为0的第二个RunID加入Member

enter image description here

我正在使用的当前代码:

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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;

答案 2 :(得分: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