如何使用自联接选择最小值和最大值

时间:2012-09-20 16:55:47

标签: mysql sql greatest-n-per-group

我有一个看起来像这样的表:

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

棘手的部分是每个客户端只有一行具有最小/最大值,然后是其他列与最小/最大值一起。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

您可以使用以下内容:

select distinct t1.client, t1.mnval, mindate.dt, t1.mxval, maxdate.dt
from
(
    select min(value) mnval, max(value) mxVal, client
    from yourtable
    group by client
) t1
inner join yourtable t2
    on t1.client = t2.client
inner join yourtable mindate
    on t1.client = mindate.client
    and t1.mnval = mindate.value
inner join yourtable maxdate
    on t1.client = maxdate.client
    and t1.mxVal = maxdate.value