SQL - 在一个字段中选择具有来自另一个字段的最高记录的不同记录

时间:2010-01-25 04:01:38

标签: sql sql-server tsql sql-server-2008 ranking

在我有这样一个表格的情况下:

int id (PK)
int staff_id
int skill_id
bit mainskill

我想为每个工作人员(由staff_id表示)仅选择一条记录,列出他们的主要技能,如(1)在mainskill中所示。如果没有主要技能,我想返回该工作人员的任何技能记录。例如:

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

查询应返回:

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

我尝试了各种分组,DISTINCT等组合,但无法获得我之后的输出。任何帮助表示赞赏。

4 个答案:

答案 0 :(得分:7)

SQL Server 2005+,使用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 +,非CTE等效项:


  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

两者都使用ROW_NUMBER,它仅在SQL Server 2005之后可用。

答案 1 :(得分:1)

如果你连接技能人员前面的主要技能,那么max会给你一个mainskill或另一个mainskill不存在。

SELECT t.id,          t.staff_id,          t.skill_id,          t.mainskill, FROM TABLE t WHERE CAST(t.mainskill As Varchar(5))+' - '+ Cast(t.skill_id as varchar(5)) 在 (SELECT MAX(CAST(t.mainskill As Varchar(5))+' - '+ Cast(t.skill_id as varchar(5)))FROM 表t GROUP BY t.staff_id)

答案 2 :(得分:0)

<强>的MySQL

select * from staff_skill;

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          

7 rows selected


select * from staff_skill x
where skill_id =
(select y.skill_id from staff_skill y
where y.staff_id = x.staff_id 
order by y.mainskill desc, y.skill_id desc limit 1);

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

3 rows selected

- Ian

答案 3 :(得分:0)

<强>的Oracle

怎么样:

(staff_skill是你的桌子)

select * from staff_skill x where
skill_id =
(select skill_id from 
(select * from staff_skill 
order by mainskill desc, skill_id desc)
where staff_id = x.staff_id and rownum = 1);