简体   繁体   中英

Using a 'rank' to return 'top' row in SQL

I have a data set that returns clients services, like the table below:

PERSON_ID   SERVICE_CATEGORY   SERVICE_RANK
1234        BLOW DRY           3  
1234        CUT AND COLOUR     2
1234        RESTYLE            1
4321        BLOW DRY           3
4321        CUT AND COLOUR     2
4321        FRINGE TRIM        1

(No idea why I used haircutting, its actually sensitive data and I just cant use that itself)

So I need to run a report of all Services above, but I only want it to bring back the highest Service_Rank (1-10 lets say, with 1 being the most important)

This would then bring back whichever the highest was, even if that was Rank 3, but that would be what we would class of most importance.

In this instance, I would expect it to return

PERSON_ID   SERVICE_CATEGORY   SERVICE_RANK 
1234        RESTYLE            1
4321        FRINGE TRIM        1

I hope this makes sense. At the moment its a view, using a variety of tables to bring the data through, and ideally this would form part of my Select statement.

Unfortunately, I am just learning SQL and as such need as much help as I can get!

Thanks in advance (I couldnt find anything that addressed this issue)

Nikki

;WITH CTE as
(
  SELECT 
    PERSON_ID, SERVICE_CATEGORY, SERVICE_RANK, 
    row_number() over (partition by PERSON_ID order by SERVICE_RANK) rn
  FROM
    yourtable
)
SELECT 
  PERSON_ID, SERVICE_CATEGORY, SERVICE_RANK
FROM CTE
WHERE rn = 1

One way would be to use a subquery to get the max rank

select person_id, service_category, service_rank
from your_table
where service_rank = (select min(service_rank) from your_table)

This would return the two rows with SERVICE_RANK 1.

Another way is to use a window function to number the rows:

select person_id, service_category, service_rank 
from (
    select 
       person_id, service_category, service_rank, 
       rn = row_number() over (partition by person_id order by service_rank asc)
    from your_table
) a where rn = 1

Assuming you're using MSSQL and only want one row:

SELECT
TOP 1 
* 
FROM haircuts 
ORDER BY service_rank

If you want all rows with the highest service rank then:

SELECT * 
FROM haircuts 
WHERE service_rank = 
( SELECT MIN(service_rank) from haircuts);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM