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

トリッキーな部分は、最小/最大値を持つクライアントごとに1つの行のみを取得し、次にそれらの最小/最大値に沿った他の列を取得することです。何か案は?

4

2 に答える 2

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 に答える
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 に答える