0

Possible Duplicate:
Fetch the row which has the Max value for a column

I have two tables

1. A table USER with a USER_ID, NAME, ...
2. A table STATUS with a STATUS_ID, PEOPLE_FK (foreign key to USER_ID), LABEL, DATE_START...

A USER can only have one active status. I use the DATE_START field to keep the history of all status of the user. I never delete a status. If I create a join between USER and STATUS I can easely get all my users with all they status. BUT I would like to create a query to retriev all my users with they last status only. Is it possible ? What shoul I use ?

Community
  • 1
  • 1
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200

4 Answers4

0

Join like this:

SELECT *
FROM USER   U
JOIN STATUS S ON U.USER_ID = S.USER_ID
              AND NOT EXISTS (
                SELECT 1 
                FROM   STATUS S2
                WHERE  S2.USER_ID = S.USER_ID 
                AND    S2.START_DATE > S.START_DATE
              )

This will only join those status records for which there doesn't exist another status for the same user and with a more recent date

Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
0

try

select * from user 
inner join 
(
   select * from status
   inner join 
      (select max(Date_start) as maxdate, status_id as id  
           from status group by Status_id)   d
   on status_id = d.id and Date_start = d.maxdate
)d1 
on userid =d1.People_fK
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
0

I assume that you're using SQL-Server :

You can use a cte with ROW_NUMBER function:

WITH CTE AS
(
    SELECT U.USER_ID, U.NAME, U.DATE_START, S.STATUS
    ,   RN = ROW_NUMBER()OVER(PARTITION BY S.STATUS_ID ORDER BY U.DATE_START DESC)
    FROM USER U INNER JOIN STATUS S ON U.User_ID=S.PEOPLE_FK
)
SELECT * FROM CTE WHERE RN = 1
Bastien Vandamme
  • 17,659
  • 30
  • 118
  • 200
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0
select * from 
    user a, 
    status b 
where 
      a.user_id = b.poeple_id 
  and b.start_date = (select max(start_date) 
                             from status c 
                             where c.people_id=b.people_id)
Ahmad
  • 12,336
  • 6
  • 48
  • 88