我需要使用2个不同的表对数据进行排序。在表A中,我有用户连续插入的顺序,在表B中,我有使用表A中的顺序和来自2个名为“IdMetadata”的表中的链接列获得的值。数据:
declare @table1 table(idMetadata int, Orden int identity)
insert into @table1 values (15)
insert into @table1 values (16)
select * from @table1
declare @table2 table(idDet int, idEnc int, IDMetadata int, OrderValue int)
insert into @table2 values (185441, 22008, 15, 7)
insert into @table2 values (187777, 22269, 15, 7)
insert into @table2 values (211259, 24925, 15, 7)
insert into @table2 values (251476, 29431, 15, 4)
insert into @table2 values (185442, 22008, 16, 6)
insert into @table2 values (187778, 22269, 16, 6)
insert into @table2 values (211260, 24925, 16, 6)
insert into @table2 values (251477, 29431, 16, 5)
主要问题是我必须使用名为“OrderValue”的字段以升序创建一个从表B获取值并且具有表A(黄色行)的连续顺序的查询。
以下查询是我到目前为止的基本想法
select distinct t3.idEnc, t3.IDMetadata, t3.OrderValue
from @table1 t1
inner join @table2 t2
on t1.idMetadata = t2.IDMetadata
inner join @table2 t3
on t2.idEnc = t3.idEnc
order by t3.idEnc desc, t3.IDMetadata asc, t3.OrderValue asc
答案 0 :(得分:3)
根据您的评论,这就是您要做的事情。
select * from @table2 where idenc in (
select distinct t15.idEnc
from @table1 t1
inner join (select * from @table2 where IDmetadata = 15) t15
on t1.idMetadata = t15.IDMetadata
inner join (select * from @table2 where IDmetadata = 16) t16
on t15.idenc=t16.idenc
where t16.ordervalue > t15.ordervalue
)
order by idenc,idmetadata,ordervalue