Need help to achieve the following result.
I have the following table entries ordered by name
Name Rank ---------- A 1 B 1 C 2 D 1 E 2
I am in an attempt to write an sql query to get the following results
Name Rank --------- A 1 B 1
The condition is like as soon as we find rank > 1 stop further traversal and return all items prior to the 1st matched row in this example all rows prior to Name 'C'
SELECT
*
FROM
(
SELECT
ROW_NUMBER() OVER ( ORDER BY name) AS name_row_number,
ROW_NUMBER() OVER (PARTITION BY rank ORDER BY name) AS rank_row_number,
yourTable.*
FROM
yourTable
)
ordered
WHERE
name_row_number = rank_row_number
The example below shows that only for the first two rows do these ROW_NUMBER()
values match.
Name Rank name_row_number rank_row_number
---------------------------------------------
A 1 1 1
B 1 2 2
C 2 3 1
D 1 4 3
E 2 5 2
I can't imagine that it's very efficient on large data sets though.
SELECT * FROM
(
SELECT name,rank FROM test
ORDER BY name,rank
)
WHERE RowNum < (
select min(rnk)
from (
SELECT
case rank when 2 then 'x' else 'y' end as tag,
row_number() over(order by name,rank) as rnk
from test
)Z
where tag='x'
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.