gpt4 book ai didi

mysql - 如何选择与 mysql 查询中的最大日期对应的值

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

我正在尝试编写一个查询,它根据 ID 从表组中获取最大值和最小值。基本上,我有一个表格,可以从现有的 contract_id 中添加新年度金额的续订:

customer_id | contract_id | start_date | end_date   | revenue6           | 125         | 2012-01-01 | 2012-12-31 | 10,0006           | 126         | 2012-01-01 | 2013-12-31 | 5,0006           | 125         | 2013-01-01 | 2013-12-31 | 12,0006           | 126         | 2014-01-01 | 2015-12-31 | 8,000

我想要的是最小开始日期、最大结束日期和该结束日期的相应收入,按给定 customer_id 的 contract_id 分组。

因此,查询理想情况下会返回:

customer_id | contract_id | start_date | end_date   | revenue6           | 125         | 2012-01-01 | 2013-12-31 | 12,0006           | 126         | 2012-01-01 | 2015-12-31 | 8,000

我可以得到 max 的东西,但是我在同一个查询中同时提取 MAX 和 MIN 时遇到了问题。任何帮助将不胜感激。谢谢!

最佳答案

您应该试试这个查询,还可以查看屏幕截图进行验证(参见图 1)

SELECT r.`contract_id`,r.`start_date`,
(SELECT sub_r.`end_date` FROM `table` sub_r where sub_r.`contract_id` = r.`contract_id`
ORDER BY sub_r.`revenue` DESC limit 1 )
AS `end_date`,
(SELECT sub_r.`revenue` FROM `table` sub_r where sub_r.`contract_id` = r.`contract_id`
ORDER BY sub_r.`revenue` DESC limit 1 )
AS `revenue`
FROM `table` r GROUP BY r.`contract_id`;

Image 1

enter image description here

关于mysql - 如何选择与 mysql 查询中的最大日期对应的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10566739/

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