Por ejemplo que tenemos una tabla de artículos y una tabla de códigos de barra relacionados con dicho artículo y necesitamos por cada artículo 1 solo código de barra porque con esto sabremos si tiene barra o no y no requerimos todos los códigos de barra. / For example we have an articles table and barcodes table, we need for each article show just 1 barcode that will show that the article has barcode no matter how many.
Estas serían las tablas / example tables:
create table #tmpartic(codigo varchar(10), nombre varchar(50))
insert into #tmpartic values('001', 'KEYBOARD / TECLADO')
insert into #tmpartic values('002', 'MOUSE / RATON')
insert into #tmpartic values('003', 'PEN / LAPICERO')
insert into #tmpartic values('004', 'DISPLAY / MONITOR')
insert into #tmpartic values('005', 'HARD DISK / DISCO DURO')
create table #tmpbars(article varchar(10), codbar varchar(20))
insert into #tmpbars values('001', '8909001212')
insert into #tmpbars values('001', '8909001213')
insert into #tmpbars values('001', '8909001214')
insert into #tmpbars values('003', '8909051223')
insert into #tmpbars values('004', '8909061245')
insert into #tmpbars values('005', '8909071241')
Ahora vamos a seleccionar con un left normal / select with a normal “left” query :
select art.codigo, art.nombre, isnull(bar.codbar,'') as codbar from #tmpartic art left join #tmpbars bar on art.codigo=bar.article
Esto nos retorna todos los registros repetidos artículos en barras, se puede ver el artículo 001 que se repite 3 veces / this is returning 3 repeated records of the article 001:
Ahora veamos la magia, vamos a usar la instrucción que nos retornará solo 1 registro relacionado / Now let’s watch the magic, with this instruction we will have only 1 related record:
select art.codigo, art.nombre, isnull(bar.codbar,'') as codbar from #tmpartic art outer apply(select top 1 article, codbar from #tmpbars where article=art.codigo) bar
Resultado, no se repiten los registros de barras y sale solo 1 barra / This is the result, just 1 barcode for each article:
Podemos usar este sql cuando necesitamos filtrar repetidos desde la misma ejecución de la sentencia SQL. / We can use this sql when we need to filter repeated records since the start of the Sql sentence.