2

I have a table, named as 'person_data':-

    id   req_type    reqp_id reqt_id  dev_id
    1    track       11     12      33
    2    stop_track  11     12      33
    3    track       12     13      44
    4    stop_track  12     13      44
    5    track       12     13      45
    6    track       13     14      55

Now the condition is i want:-

  1. Only last row for those rows which have "reqp_id, reqt_id, dev_id" column duplicate.
  2. All rows if they don't have these three column as duplicate. and situation is something like we can not use IN operator.

What i tried is :-

select max(id),min(req_type),reqp_id, reqt_id, dev_id 
from person_data group by reqp_id, reqt_id, dev_id;

and the output is exactly same as i want:-

id  req_type    reqp_id reqt_id dev_id
2   stop_track  11      12      33
4   stop_track  12      13      44
5   track       12      13      45
6   track       13      14      55

and if i used:-

select max(id),max(req_type),reqp_id, reqt_id, dev_id 
from person_data group by reqp_id, reqt_id, dev_id;

then the output changed in only "req_type" column as :-

req_type 
track
track 
track
track

But output is clearly describing that max or min function sorting the values using alphabetical order that i don't want otherwise if someone change the values of "req_type" column then output will be changed. thanks in advance,

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
Krishna
  • 795
  • 2
  • 7
  • 24
  • possible duplicate of [Retrieving the last record in each group](http://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group) – Ken Y-N Jun 13 '14 at 04:43

1 Answers1

2

Try this

SELECT T.* FROM person_data T JOIN
(
  SELECT Max(id) as maxid,reqp_id, reqt_id, dev_id 
  FROM person_data 
  GROUP BY reqp_id, reqt_id, dev_id
) S
ON T.id = S.maxid

Fiddle Demo

Output would be:


id  req_type    reqp_id reqt_id dev_id
2   stop_track  11      12      33
4   stop_track  12      13      44
5   track       12      13      45
6   track       13      14      55
Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
  • 1
    Hi Vignesh, thanks actually your query is mostly correct but getting max(id) one more column which i don't want so we have to use SELECT T.* FROM person_data T Inner JOIN ( SELECT Max(id) as maxid,reqp_id, reqt_id, dev_id FROM person_data GROUP BY reqp_id, reqt_id, dev_id ) S ON T.id = S.maxid to get the correct output – Krishna Jun 13 '14 at 05:11