gpt4 book ai didi

mysql - 如何使用自连接选择最小值和最大值

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

我有一个如下所示的表格:

pk client value date
1 001 564 2012/5/1
2 002 245 2012/6/1
3 003 445 2012/6/6
4 001 845 2012/7/1
5 002 567 2012/8/1
6 001 123 2012/9/1

我知道这可以通过每组最大的 n 和自连接来解决,但我很难弄清楚。

基本上这就是我想要的输出

client min(value) max(value) date_for_min(value) date_for_max(value)
001 123 845 2012/9/1 2012/7/1
002 245 567 2012/6/1 2012/8/1
003 445 445 2012/6/6 2012/6/6

棘手的部分是为每个客户端仅获取一行具有最小/最大值的行,然后获取与这些最小/最大值相关的其他列。有什么想法吗?

最佳答案

如果某个最小值或最大值有多个行(对于同一客户端),我已经为您提供了它们出现的最早日期:

select t1.client, t1.MinValue, t1.MaxValue, min(t2.date) as date_for_min_value, min(t3.date) as date_for_max_value
from (
select client, min(value) as MinValue, max(value) as MaxValue
from MyTable
group by client
) t1
inner join MyTable t2 on t1.client = t2.client and t1.MinValue = t2.Value
inner join MyTable t3 on t1.client = t3.client and t1.MaxValue = t3.Value
group by t1.client, t1.MinValue, t1.MaxValue

关于mysql - 如何使用自连接选择最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12517298/

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