tags:

views:

48

answers:

4

Hi ,

My table is like

ID    FName LName Date(mm/dd/yy) Sequence Value
101   A      B    1/10/2010      1       10 
101   A      B    1/10/2010      2       20
101   X      Y    1/2/2010       1       15
101   Z      X    1/3/2010       5       10
102   A      B    1/10/2010      2       10 
102   X      Y    1/2/2010       1       15
102   Z      X    1/3/2010       5       10

I need a query that should return 2 records

101   A      B    1/10/2010      2       20
102   A      B    1/10/2010      2       10 

that is max of date and max of sequence group by id.

Could anyone assist on this.

A: 

Can you write clearly your schema and data? You should write like you see in a table of data...

Muktadir
A: 
-----------------------
-- get me my rows...
-----------------------
select * from myTable t
-----------------------
-- limiting them...
-----------------------
inner join 
----------------------------------
-- ...by joining to a subselection
----------------------------------
(select m.id, m.date, max(m.sequence) as max_seq from myTable m inner join
        ----------------------------------------------------
        -- first group on id and date to get max-date-per-id
        ----------------------------------------------------
        (select id, max(date) as date from myTable group by id) y
        on m.id = y.id and m.date = y.date
group by id) x

on t.id = x.id
and t.sequence = x.max_seq

Would be a simple solution, which does not take account of ties, nor of rows where sequence is NULL.

EDIT: I've added an extra group to first select max-date-per-id, and then join on this to get max-sequence-per-max-date-per-id before joining to the main table to get all columns.

davek
But It should be grouped by id and also i need max date and max sequence for the date
Aswini
A: 

I have considered your table name as employee.. check the below thing helped you.

 select * from employee emp1
    join (select Id, max(Date) as dat, max(sequence) as seq from employee group by id)  emp2
    on emp1.id = emp2.id and emp1.sequence = emp2.seq and emp1.date = emp2.dat
Jothi
in emp2 you might well end up with max(date) and max(sequence) coming from different rows: I don't think that's what the OP is looking for.
davek
A: 

I'm a fan of using the WITH clause in SELECT statements to organize the different steps. I find that it makes the code easier to read.

WITH max_date(max_date)
AS (
  SELECT MAX(Date)
  FROM my_table
),

max_seq(max_seq)
AS (
  SELECT MAX(Sequence)
  FROM my_table
  WHERE Date = (SELECT md.max_date FROM max_date md)
)

SELECT *
FROM my_table
WHERE Date = (SELECT md.max_date FROM max_date md)
AND Sequence = (SELECT ms.max_seq FROM max_seq ms);

You should be able to optimize this further as needed.

Leons