Search code examples
sqlsql-servergroup-byhaving

Query to return just unique value from last column


I have a query that returns everything as wanted. But I do not want duplicates. Already tried "group by" but I get the exact same result.

select distinct eq.id as id, tipo.descripcion as tipoId, eq.tagId, eq.periodoId, eq.asignado, op.numOpcion as empleadoId
from Empleados emp inner join dbo.Opciones op ON op.empleadoId = emp.id 
inner join dbo.TipoEquipo tipo ON tipo.id = op.tipoEquipoId 
inner join dbo.Equipos eq ON eq.tipoId = tipo.id
where emp.Id = 1 
order by op.numOpcion

I get this.

id  tipoId  tagId   periodoId   asignado    empleadoId
1   Macbook tag1           1    Si             1
3   iMac    tag3           1    Si             2
5   Dell Lap OP tag5       1    No             3
6   Dell Lap OP tag6       1    No             3

Trying to get unique (the first value for empleadoId). Like this.

id  tipoId  tagId   periodoId   asignado    empleadoId
1   Macbook tag1           1    Si             1
3   iMac    tag3           1    Si             2
5   Dell Lap OP tag5       1    No             3

Thanks.


Solution

  • You get duplicate rows because you have a eq.id which has unique id so, you can remove it or use row_number() :

    select top (1) with ties eq.id as id, tipo.descripcion as tipoId, eq.tagId, eq.periodoId, eq.asignado, op.numOpcion as empleadoId
    from Empleados emp inner join 
         dbo.Opciones op 
         ON op.empleadoId = emp.id inner join 
         dbo.TipoEquipo tipo 
         ON tipo.id = op.tipoEquipoId inner join 
         dbo.Equipos eq 
         ON eq.tipoId = tipo.id
    where emp.Id = 1 
    order by row_number() over (partition by tipo.descripcion, eq.periodoId, eq.asignado, op.numOpcion order by eq.id desc);