I have the following query on sql server, the goal is to bring the records of the Personas
table that are related to ListaMarketing_persona
but since this is an AnyToAny table that joins ListaMarketing
, there may be several people related to various Mark lists. my query was the following:
SELECT
distinc
p.Id,
p.Nombres,
p.ApellidoPaterno,
p.ApellidoMaterno,
count(1) over (partition by null) TotalRegistros,
ROW_NUMBER() over ( ORDER BY p.FechaActualizacion DESC ) AS RowNum,
FROM Personas as p
inner join Estados as e on p.EstadoId=e.Id
inner join ListaMarketing_Persona as lmpe on p.Id=lmpe.IdPersona
inner join ListaMarketing as lm on lmpe.IdListaMarketing=lm.Id
where lmpe.IdListaMarketing in (select Id from @Temp_LstMark)
With distinc
I can avoid duplicates, but I need the ROw_NUMBER()
but this makes that happen:
ID Nombres ApellidoPate ApellidoMate TotReg ROwNum
170112 Juan Quispe Santos 53 22
170111 Vit Ali Cruz 53 23
46 SARA ABIGAILL HUAHUAMULLO MAMANI 53 24
31 ELIZABETH QUISPE 53 25
28 CARLA IONEE CABANILLAS GALLARDO 53 26
28 CARLA IONEE CABANILLAS GALLARDO 53 27
27 VICTOR ELVIS ALVAREZ 53 28
The RowNum
makes the distinction not work, in the duplicate data, and the record is doubled in 28
I decided to use is DENSE_RANK()
.
SELECT
distinc
p.Id,
--count(1) over (partition by null) TotalRegistros,
DENSE_RANK() OVER (ORDER BY p.FechaActualizacion DESC) AS RowNum,
This does not duplicate anymore. but I get this result:
index ID Nombres ApePaterno ApeMaterno TotaReg RowNum
47 33 ELSA CUAYLA 53 46
48 30 JIMY JUAN CASTILLO QUISPE 53 47
49 26 ODALIZ SHARON ALVAREZ ARREDONDO 53 48
You can see all the records that are a total of 49 , but the total number of records keeps coming 53