Friday, May 30

select n rows per group from a table

Suppose, after doing group by, you want to select a specific number of rows from each group.

1. How to select one row per group from a table ?

There are many ways to achieve this. But the simplest I feel, is as below.
Use min/max on one of the available columns and then implement group by

--#
Get first/lowest row from each group.
select col_1, min(col_2) from yourTable group by col_1

--# Get last/highest row from each group.
select col_1, max(col_2) from yourTable group by col_1

2. How to select n rows per group, from a table ?

Make sure you have unique combination of col_1, col_2 in you table. If not you can
delete duplicates from the table
or you can move the data to a temp. table and execute below on the temp table.

--#Get first n rows per group from a table
select distinct * from yourTable A where
( select count(*) from yourTable B where A.col_1 = B.col_1 and A.col_2 > B.col_2 ) < n

--#Get first 3 rows per group from a table
select distinct * from yourTable A where
( select count(*) from yourTable B where A.col_1 = B.col_1 and A.col_2 > B.col_2 ) <>

--#Get last 3 rows per group from a table
select distinct * from yourTable A where
( select count(*) from yourTable B where A.col_1 = B.col_1 and A.col_2 <>


Ref. Table :
create table yourTable ( col_1 varchar(10) , col_2 int )
go

insert into yourTable values ( 'red', 1)
insert into yourTable values ( 'red', 10)
insert into yourTable values ( 'blue', 11)
insert into yourTable values ( 'blue', 12)
insert into yourTable values ( 'blue', 13)
insert into yourTable values ( 'yellow', 100)
insert into yourTable values ( 'yellow', 211)
go


0 comments:





Disclaimer :
Unless, otherwise mentioned, TF's SQL tips/tricks are for Sybase ASE 12.5.x