I am trying to get the results of the query below:
select distinct
REQ_ID
, ID
, MAX(STEP) as step
, SUBSTRING(p1.NAME,9, len(p1.NAME)) as _index_
, p2.value as location
from HISTORY h
LEFT JOIN Parameter p1
on p1.WP_ID=h.ID
AND ( ( p1.NAME like 'name_'
AND p1.VALUE like h.ID COLLATE DATABASE_DEFAULT )
OR ( p1.NAME like 'name__'
AND p1.VALUE like h.ID COLLATE DATABASE_DEFAULT) )
LEFT JOIN Parameter p2
on p2.WP_ID=h.ID
AND p2.PA_NAME = 'Location' + (SUBSTRING(p1.NAME,9, len(p1.NAME)) )
WHERE h.ROLE = 'rock'
GROUP BY REQ_ID, ID, step, p1.name, p2.value
The problem is that the query is returning more than 1 results (in my case there are 6) and the MAX(STEP) value is not returning the max, I can see values like 0,1,3,0,1,2
Is there a way to get only the result with the max(step)? the step field is varchar(1)
When dealing with
first record in a group, the often simplest approach is to useROW_NUMBER(). Without knowing more about your schema and data, I can say that the following query will work, but it may be possible to simplifiy it further…This will give only one row per
req_id, idcombination, and will always pick the row with the higheststepvalue.NOTE: I don’t know if the
GROUP BYis still needed. I left it in simply because you had it.