Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - select distinct records in one field with highest records from another field

In a scenario where I have a table like so:

int id (PK)
int staff_id
int skill_id
bit mainskill

I want to select only ONE record for each staff member (represented by staff_id) listing their main skill as represented by a (1) in mainskill. If no main skill is present, I want to return any of the skill records for that staff member. For example:

id   staff_id   skill_id   mainskill
1    1          24         1
2    1          55         0
3    1          7          0
4    4          24         0
5    4          18         0
6    6          3          0
7    6          18         1

The query should return:

id   staff_id   skill_id   mainskill
1    1          24         1
4    4          24         0
7    6          18         1

I've tried various combinations of grouping, DISTINCT etc but can't get the output I'm after. Any help appreciated.

like image 431
user258133 Avatar asked Feb 28 '23 17:02

user258133


1 Answers

SQL Server 2005+, Using CTE:


WITH rows AS (
  SELECT t.id,
         t.staff_id,
         t.skill_id,
         t.mainskill,
         ROW_NUMBER() OVER (PARTITION BY t.staff_id ORDER BY t.mainskill DESC) AS rank
    FROM TABLE t)
  SELECT r.id,
         r.staff_id,
         r.skill_id,
         r.mainskill
    FROM rows r
   WHERE r.rank = 1
ORDER BY r.staff_id

SQL Server 2005+, Non-CTE Equivalent:


  SELECT r.id,
         r.staff_id,
         r.skill_id,
         r.mainskill
    FROM (SELECT t.id,
                 t.staff_id,
                 t.skill_id,
                 t.mainskill,
                 ROW_NUMBER() OVER (PARTITION BY t.staff_id ORDER BY t.mainskill DESC) AS rank
            FROM TABLE t) r
   WHERE r.rank = 1
ORDER BY r.staff_id

Both use ROW_NUMBER, which is only available since SQL Server 2005.

like image 94
OMG Ponies Avatar answered Mar 02 '23 12:03

OMG Ponies