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)
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.
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.
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.
WITH Enumerated AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY Tag ORDER BY Sequence) AS RN
FROM MyTable
)
SELECT * FROM Enumerated WHERE RN = 4;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With