I am using SQL 2008 to query using inner join:
SELECT t2.intencion_id,t2.numpago,t3.orden,t2.importe
,SUM([importeaplicado]) AS importeaplicado
,t3.intfinanciamiento_interes
,t1.[estatus] FROM [APLICACIONES] as t1
inner join movcargos as t2 on t1.idmovcargo=t2.idmovcargo
inner join intenciones_financiamiento as t3 on (t2.intencion_id=t3.intencion_id and t2.numpago=t3.intFinanciamiento_pagoNumero) where t2.idtipomovimiento=1 and t1.estatus='A' GROUP BY t2.intencion_id,numpago,importe,t1.estatus,intfinanciamiento_interes,t3.orden order by intencion_id,numpago,orden desc
among the columns that this query returns, there are 3 that are repetitive series: intention_id, numpago and order but I want it to show the records of all the intention_id, all the numpago but only the highest order
How can I do this filtering?
As I commented, the question is not very clear. But my interpretation is that for any series of records that share the same values for the join
intencion_id, numpago
, you only want to return the record that has the highest value for the columnorden
.If that is the case, this can be achieved using
row_number()
to filter those records:There's probably a better way to achieve what you're asking for, but you'd have to describe your tables better.
I don't fully understand the data but I'm going to assume the following:
orden
, that is, if theorden
largest is5
, you will always get results with1, 2, 3, 4 y 5
the order of which you will always want the oforden 5
.If the above is true, the solution would be this:
Of course I recommend using
having by
so if you confirm that this solution works it might help you to write it in other more optimal ways.