I have a table Peticiones
whose design is:
NPeticion - nvarchar
FechaApertura - date
TipoPeticion - nvarchar
FechaResolucion - nvarchar
...
(más campos, irrelevantes para este asunto)
The question is that I try to make a query that eliminates duplicates of records that have the same NPeticion
, FechaApertura
and TipoPeticion
stay with the record with FechaResolucion
more recent and different from 'NULL'
unless all the records are 'NULL'
that I would stay with any of them.
I made this query: (possibly not the most elegant / efficient but that's what I came up with)
;with aBorrar as
(select [NPeticion], [FechaApertura], [TipoPeticion],[FechaResolucion],
row_number() over(partition by [NPeticion], [FechaApertura]
order by [FechaResolucion] desc) rn
from [dbo].[Peticiones]
where NPeticion in (
SELECT
[NPeticion]
FROM
[dbo].[Peticiones]
GROUP BY
[NPeticion],FechaApertura, TipoPeticion
HAVING
COUNT(*) > 1
)
and [FechaResolucion] <> 'NULL'
Union
select [NPeticion], [FechaApertura], [TipoPeticion],[FechaResolucion],2
from [dbo].[Peticiones]
where NPeticion in (
SELECT
[NPeticion]
FROM
[dbo].[Peticiones]
GROUP BY
[NPeticion],FechaApertura, TipoPeticion
HAVING
COUNT(*) > 1
)
and [FechaResolucion] = 'NULL'
)
select *
from aBorrar
where rn > 1;
Explanation:
Since FechaResolucion
is a nvarchar
, if I order desc
to keep the most recent, the values 'NULL'
appear first. That's why I make a select ordering the records that are not 'NULL'
and then union of those null.
But that does not solve the problem of if all the duplicates contain that column equal to 'NULL'
I would erase them all ...
How do I leave a record in case all duplicates have FechaResolucion = 'NULL'
?
Sample data:
[NPeticion] [FechaApertura] [TipoPeticion] [FechaResolucion]
'20171204000001' 12/04/2017 'A' '12/04/2017'
'20171204000001' 12/04/2017 'A' '10/04/2017'
'20171204000001' 12/04/2017 'A' '10/04/2017'
'20171204000001' 12/04/2017 'A' 'NULL'
'20171204000002' 12/04/2017 'B' 'NULL'
'20171204000002' 12/04/2017 'B' 'NULL'
Current result (records that would be deleted):
[NPeticion] [FechaApertura] [TipoPeticion] [FechaResolucion]
'20171204000001' 12/04/2017 'A' '10/04/2017'
'20171204000001' 12/04/2017 'A' '10/04/2017'
'20171204000001' 12/04/2017 'A' 'NULL'
'20171204000002' 12/04/2017 'B' 'NULL'
'20171204000002' 12/04/2017 'B' 'NULL'
Expected result (records that would be deleted):
[NPeticion] [FechaApertura] [TipoPeticion] [FechaResolucion]
'20171204000001' 12/04/2017 'A' '10/04/2017'
'20171204000001' 12/04/2017 'A' '10/04/2017'
'20171204000001' 12/04/2017 'A' 'NULL'
'20171204000002' 12/04/2017 'B' 'NULL'
Note: I have not designed the BD. Modifying your design is not possible.