Efficiently selecting "sub maxes" from SQL Table
Apologies for the title, I am unsure how to 开发者_开发百科express my problem... I have a table that looks something like this:
A | B
--------------
01 | 1
01A | 1
01B | 1
01C | 1
02 | 1
03 | 1
03 | 2
03A | 1
03B | 1
Sometimes column A is qualified with a letter (##A,##B
), sometimes it is not (##
). I would need to
SELECT A,B from Table
if there were no suffixes. With the suffix, however, I need to select the maximum value of A for each B. (That was phrased poorly). I would expect the following results for the table above:
A | B
--------------
01C | 1
02 | 1
03 | 2
03B | 1
Right now, I am using a subselect and my query is:
SELECT A,B FROM Table t1
WHERE t1.A = (SELECT MAX(t2.A) FROM Table t2WHERE LEFT(t1.A,2) = LEFT(t2.A,2)
This is incredibly inefficient, however, and my table is pretty large, so they query is taking far too long to run. Is there a better way?
Thanks!
;with cteRowNumbers as (
select A, B, ROW_NUMBER() over(partition by B, left(A,2) order by A desc) as RowNumber
from YourTable
)
select A, B
from cteRowNumbers
where RowNumber = 1
order by A
If you find common table expressions unpleasant, there's this which is essentially the same thing as the CTE example.
SELECT V.*
FROM (
SELECT
A
,B
,ROW_NUMBER()OVER(PARTITION BY B,LEFT(A,2) ORDER BY A DESC) AS RowNumber
FROM YourTable
) AS V
WHERE V.RowNumber = 1
精彩评论