Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find N element in sequence using SQL

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)

like image 369
Sam Saffron Avatar asked Sep 08 '10 01:09

Sam Saffron


People also ask

How do you find the nth value in SQL?

ROW_NUMBER (Window Function) ROW_NUMBER (Window Function) is a standard way of selecting the nth row of a table. It is supported by all the major databases like MySQL, SQL Server, Oracle, PostgreSQL, SQLite, etc.

How do I query sequence in SQL?

The syntax to a view the properties of a sequence in SQL Server (Transact-SQL) is: SELECT * FROM sys. sequences WHERE name = 'sequence_name'; sequence_name.

How do I find the next number in a sequence in SQL?

Use it for determining the order in which rows were inserted and the order in which the Seq values should be generated. Then use ROW_NUMBER to generate values of Seq partitioned by Model (the sequence restarts from 1 for each value of Model ) as needed in the query.


1 Answers

WITH Enumerated AS (
  SELECT *, ROW_NUMBER() OVER (PARTITION BY Tag ORDER BY Sequence) AS RN 
  FROM MyTable
)
SELECT * FROM Enumerated WHERE RN = 4;
like image 144
Bill Karwin Avatar answered Oct 19 '22 13:10

Bill Karwin