gpt4 book ai didi

带有 "Group by"和 "max"和 "join"的 SQL 请求?

转载 作者:行者123 更新时间:2023-11-29 07:14:25 25 4
gpt4 key购买 nike

这是我的数据示例:

客户属性:

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,但我想它与任何数据库系统应该没有太大区别)

最佳答案

您应该能够按如下方式使用子查询:

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

关于带有 "Group by"和 "max"和 "join"的 SQL 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2363237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com