问题
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:
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);
来源:https://stackoverflow.com/questions/2363237/sql-request-with-group-by-and-max-and-join