带有“分组依据”和“最大”和“加入”的SQL请求?

时间:2010-03-02 13:07:58

标签: sql mysql group-by inner-join

以下是我的数据样本:

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
----------+-------------+---------

客户:

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

我想获取表“CLIENT_ATTRIBUT”中的每个ID_CLIENT:
ID_CLIENT,max(DATE_CLIENT)及其对应的“ATTRIBUT”和“NOM_MARITAL”

所以在上面的例子中:

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

(我正在使用Mysql,但我想它不应该与任何数据库系统如此不同)

1 个答案:

答案 0 :(得分:2)

您应该能够使用子查询,如下所示:

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);