Skip to Main Content
  • Questions
  • how to get a min from pairs (might be analytic function involved)

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, mega.

Asked: June 15, 2016 - 3:49 am UTC

Last updated: June 15, 2016 - 5:34 am UTC

Version: 11

Viewed 1000+ times

You Asked

Hi,
I have unique pairs:
id1 id2 x
---------------------
1 2 0.852
1 3 0.433
1 4 0.538
2 3 0.991
2 4 0.604
3 4 0.597

how to get a one unique id column table with a minimum for each value from both parts of pairs like:
id minx
--------
1 0.433
2 0.604
3 0.433
4 0.538

thanks

and Connor said...


SQL> drop table t purge;

Table dropped.

SQL> create table t ( x int, y int, z number );

Table created.

SQL>
SQL>
SQL> insert into t values (1,2,0.852 );

1 row created.

SQL> insert into t values (1,3,0.433 );

1 row created.

SQL> insert into t values (1,4,0.538 );

1 row created.

SQL> insert into t values (2,3,0.991 );

1 row created.

SQL> insert into t values (2,4,0.604 );

1 row created.

SQL> insert into t values (3,4,0.597 );

1 row created.

SQL>
SQL> select val, min(z)
  2  from
  3    ( select x val, z from t
  4      union all
  5      select y, z from t
  6    )
  7  group by val;

       VAL     MIN(Z)
---------- ----------
         1       .433
         2       .604
         4       .538
         3       .433

4 rows selected.

SQL>
SQL>


or you could use UNPIVOT

SQL> select id, min(z)
  2  from   t
  3  unpivot (id for tag in (x as 'x', y as 'y'))
  4  group by id;

        ID     MIN(Z)
---------- ----------
         1       .433
         2       .604
         4       .538
         3       .433

4 rows selected.


Rating

  (1 rating)

Is this answer out of date? If it is, please let us know via a Comment

Comments

it's working!

mega, June 15, 2016 - 6:05 am UTC

unpivot function is awesome, thank you very much!