views:

50

answers:

1

Given the following table:

Sequence    Tag
-----       ----
1           a
2           a
3           a
88          a
100         a
1           b
7           b
88          b
101         b

I would like a query that returns the 4th in each sequence of tags (ordered by Tag, Sequence asc):

Tag         4thInSequence
-----       --------
a           88
b           101

What is the most efficient SQL I can use here? (Note: SQL Server 2008 tricks are allowed)

+7  A: 
WITH Enumerated AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Tag ORDER BY Sequence) AS RN 
  FROM MyTable
)
SELECT * FROM Enumerated WHERE RN = 4;
Bill Karwin
Thanks Bill, this is going to help make your user page less ugly, I'm getting the historic dates your badges were assigned
Sam Saffron
Yes I doubt that this will be bettered.
Martin Smith
@Bill ahh big relief, your bronze tag badges now show up in the order they were assigned :)
Sam Saffron