Selecting one arbitrarily chosen row from each group

This is a discussion on Selecting one arbitrarily chosen row from each group within the ibm-db2 forums in Other Databases category; Hi, i try to find a query for selecting one arbitrarily chosen row from each group of rows. Example: $ db2 select * from T A B C ----------- ----------- ----------- 100 1 10 100 20 2 101 3 3 3 record(s) selected. The result should be 'Select A From T group by A' but with one (B,C)- pair for each group. So {(100, 1, 10), (101, 3, 3)} and {(100, 20, 2), (101, 3, 3)} would both be valid results, but not {(100, 1, 2), (101, 3, 3)}. Is there a way to formulate this in SQL? Thanks, Ralf...

Go Back   Database Forum > Other Databases > ibm-db2

Database Forums

Register FAQ Calendar Search Today's Posts Mark Forums Read
  #1  
Old 04-25-2007, 04:13 AM
Default Selecting one arbitrarily chosen row from each group

Hi,

i try to find a query for selecting one arbitrarily chosen row from
each group of rows.

Example:

$ db2 "select * from T"

A B C
----------- ----------- -----------
100 1 10
100 20 2
101 3 3

3 record(s) selected.

The result should be 'Select A From T group by A' but with one (B,C)-
pair for each group.

So {(100, 1, 10), (101, 3, 3)} and {(100, 20, 2), (101, 3, 3)} would
both be valid results,
but not {(100, 1, 2), (101, 3, 3)}.

Is there a way to formulate this in SQL?

Thanks,
Ralf

Reply With Quote
  #2  
Old 04-25-2007, 05:29 AM
Default Re: Selecting one arbitrarily chosen row from each group

Ralf wrote:

> Hi,
>
> i try to find a query for selecting one arbitrarily chosen row from
> each group of rows.
>
> Example:
>
> $ db2 "select * from T"
>
> A B C
> ----------- ----------- -----------
> 100 1 10
> 100 20 2
> 101 3 3
>
> 3 record(s) selected.
>
> The result should be 'Select A From T group by A' but with one (B,C)-
> pair for each group.
>
> So {(100, 1, 10), (101, 3, 3)} and {(100, 20, 2), (101, 3, 3)} would
> both be valid results,
> but not {(100, 1, 2), (101, 3, 3)}.
>
> Is there a way to formulate this in SQL?


SELECT x.a, x.b, x.c
FROM ( SELECT t.*, ROW_NUMBER() OVER(PARTITION BY t.a) AS rn
FROM yourTable AS t ) AS x
WHERE x.rn = 1

A B C
----------- ----------- -----------
100 1 10
101 3 3

2 record(s) selected.


--
Knut Stolze
DB2 z/OS Utilities Development
IBM Germany
Reply With Quote
Reply


Thread Tools
Display Modes



All times are GMT -4. The time now is 09:31 AM.


Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
Integrated by bbpixel2009 :: jvbPlugin R1013.368.1

Search Engine Friendly URLs by vBSEO 3.1.0
vB Ad Management by =RedTyger=
In an effort to better serve ads to our visitors, cookies are used on Mydatabasesupport.com. For more information, check out our Privacy Policy.