views:

93

answers:

2

Here is a sample of my DATA:

CLIENT_ATTRIBUT :

ID_CLIENT | DATE_CLIENT | ATTRIBUT
----------+-------------+---------
000000001 | 2010:03:01  | 0000010
----------+-------------+---------
000000001 | 2010:02:16  | 0000010
----------+-------------+---------
000000001 | 2010:03:04  | 0000011
----------+-------------+---------
000000002 | 2010:03:01  | 0001000
----------+-------------+---------

CLIENT :

ID_CLIENT | NOM_MARITAL |
----------+-------------+
000000001 | PANTROMANI  | 
----------+-------------+
000000002 | ELLOUQUIER  |
----------+-------------+

I'd like to get, for each ID_CLIENT in the table "CLIENT_ATTRIBUT" :
ID_CLIENT, max(DATE_CLIENT) with its corresponding "ATTRIBUT", and "NOM_MARITAL"

So in the example above :

ID_CLIENT | DATE_CLIENT | ATTRIBUT | NOM_MARITAL |
----------+-------------+----------+-------------+
000000001 | 2010:03:04  | 0000011  | PANTROMANI  |
----------+-------------+----------+-------------+
000000002 | 2010:03:01  | 0001000  | ELLOUQUIER  |

(i'm working with Mysql but i guess it should not be so different with any Database System)

+1  A: 

You should be able to use a sub-query as follows:

SELECT 
    client.id_client,
    sub_query.date_client,
    client_attribut.attribut,
    client.nom_marital
FROM
    client
INNER JOIN
    (SELECT 
         client_attribut.id_client, 
         MAX(client_attribut.date_client) as date_client
     FROM 
         client_attribut
     GROUP BY 
         client_attribut.id_client)
     AS sub_query ON (sub_query.id_client = client.id_client)
INNER JOIN
    client_attribut ON (client_attribut.id_client = sub_query.id_client AND
                        client_attribut.date_client = sub_query.date_client);
Daniel Vassallo
Looks like this solution doesn't give the right "ATTRIBUT" value : In the example above, it would give "0000010" instead of "0000011" for ID_CLIENT = "000000001"
dangolive
@dangolive: My fault! Fixed now.
Daniel Vassallo
@Daniel Vassallo: Thank you very much, It does the work now ! Still a little bit complicated for me, i'll study it closer :)
dangolive
A: 

See this similar question for answers.

Greg K