0

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

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

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

4

2 回答 2

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
于 2012-09-20T17:20:08.500 回答
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
于 2012-09-20T17:01:38.897 回答