繁体   English   中英

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

[英]SQL Joining table with Min and Sec Min row

我想将表 1 与表 2 连接两次,因为我需要获得第一个最小记录和第二个最小值。 但是,我只能想到使用cte来获得第二个最低记录。 有没有更好的方法来做到这一点?

这是表:

我想将成员与输出值是 1 的输出表 FirstRunID 和输出值为 0 的第二个 RunID 连接起来

在此处输入图片说明

我正在使用的当前代码:

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

您可以为此使用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

您可以使用条件聚合来做到这一点。 根据您的结果,您不需要第一个表:

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;
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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM