Currently I need to make a query to 2 tables where the data have several equal columns. The problem is that the ordering must be done based on how the order of table A is structured, but at the same time taking the value of the ValueOrder column of table B consecutively and ascending. Sample data:
declare @table1 table(idMetadata int, Orden int identity)
insert into @table1 values (15)
insert into @table1 values (16)
insert into @table1 values (17)
select * from @table1
declare @table2 table(idDet int, idEnc int, IDMetadata int, OrderValue int, Orden int null)
insert into @table2 values (185441, 22008, 15, 7, null)
insert into @table2 values (187777, 22269, 15, 7, null)
insert into @table2 values (211259, 24925, 15, 7, null)
insert into @table2 values (251476, 29431, 15, 4, null)
insert into @table2 values (185442, 22008, 16, 6, null)
insert into @table2 values (187778, 22269, 16, 6, null)
insert into @table2 values (211260, 24925, 16, 6, null)
insert into @table2 values (251477, 29431, 16, 5, null)
insert into @table2 values (251478, 29431, 17, 6, null)
update t2
set t2.Orden = t1.Orden
from @table1 t1
inner join @table2 t2
on t1.idMetadata = t2.IDMetadata
I was able to make the following selection:
SELECT distinct A.*
FROM @table2 B1
LEFT join @table2 A
on A.idMetadata in (select a.idMetadata from @table1 A)
AND A.Orden in (select a.Orden from @table1 A)
where b1.OrderValue > a.OrderValue
But it shows me the following result:
What I need is to create a generic query that shows only those records in table B that have the same metadata and order of table A, that have internally in table B the same "idEnc" but whose field "OrderValue" be consecutive and ascending as shown in the following image with the fields marked in yellow:
Greetings