tags:

views:

171

answers:

1

I have some records in my table tbl1. There is a column s, based on which I need to retrieve the rows where datateime1 is an old date.

If I try the query shown below I seem to get correct results. Now I try to get the two oldest rows of the s1 group. I tried by adding 's1' twice to the IN clause, but that does not work, because the rows are selected by their ROWNUMBER.

So how can I rewrite the query to select a flexible number of rows per group (starting with the two oldest dates)?

Query:

SELECT
  tbl2.* 
FROM
  (
   SELECT
     a, b, c, 
     ROW_NUMBER() OVER (PARTITION BY tbl1.s ORDER BY tbl1.Datetime1)) AS RowNo 
   FROM
     tbl1 
   WHERE
     tbl1.s in ('s1','s2','s2','s3','s1','s4')
  ) AS tbl2 
WHERE
  tbl2.rowno = 1

tbl1 looks like:

a          b          c          s      Datetime1
-------------------------------------------------
samp1a     samp1b     samp1c     s1     1/1/2000
samp1a     samp1b     samp1c     s1     2/1/2000
samp1a     samp1b     samp1c     s1     3/1/2000
samp2a     samp2b     samp2c     s2     2/1/2002
samp2a     samp2b     samp2c     s2     3/1/2002
samp3a     samp3b     samp3c     s3     3/1/2000

The desired output is:

a          b          c          s      p
-------------------------------------------------
samp1a     samp1b     samp1c     s1     1/1/2000
samp1a     samp1b     samp1c     s1     2/1/2000
samp2a     samp2b     samp2c     s2     2/1/2002
samp3a     samp3b     samp3c     s3     3/1/2000
+1  A: 

I'm guessing English isn't your first language, but how about:

where tbl2.rowno=1 OR (tbl2.rowno = 2 and tbl1.s = s1)

...or whatever it is to mean "is s1"

Rob

Rob Farley
+1 Basically this is what the OP asks for, nice work figuring out the mess the original version was.
Tomalak