在SQL Server中获得每组最差5个

use*_*980 -1 sql-server

我在SQL中有一个代码,我试图让每个函数的前5个最差.我希望它能够抓住每组最差的5个而不是总体上最糟糕的5个.代码如下:

SELECT TOP (100) PERCENT Job_Function, CMX_DSC_TE, MGR_ANW_CD_Num - DES_LVL_NR_Num AS JSC_Gap
FROM  dbo.AC_GLN_Project_JSC
ORDER BY Job_Function, JSC_Gap
Run Code Online (Sandbox Code Playgroud)

该表看起来像:(这是一个较小的版本)

AG  Air Operations Tools and Equipment Knowledge    -2
AG  Capacity Planning Knowledge                     -1
AG  Conducts Research                                 -3
AG  Equipment Repair Management                     -4
AG    
AG  Equipment Repair Management                     -3
AG  Facilities, Equipment, and Grounds Maintenance  -3
AG  Facilities, Equipment, and Grounds Maintenance  -2
AG  Instructional Design Knowledge                      -2
AG  Plans Flight Operations                     -1
AG  Statistical Analysis    -2
AG  Troubleshoots Aircraft Failures            0
AG  Vendor/Supplier Management                       -3
AUTOMOTIVE  Automotive Engineering Knowledge    -1
AUTOMOTIVE  Budget Management   -3
AUTOMOTIVE  Labor Relations Knowledge   -3
AUTOMOTIVE  Mechanical Knowledge    -3
AUTOMOTIVE  Mechanical Knowledge    -3
AUTOMOTIVE  Mechanical Knowledge    -2
AUTOMOTIVE  Applies Marketing Knowledge     0
AUTOMOTIVE  Applies Service, Product, and Customer Technology Knowledge -3
Run Code Online (Sandbox Code Playgroud)

我需要它看起来像:

AG Equipment Repair Management -4
AG Facilities, Equipment, and Grounds Maintenance -3
AG Conducts Research -3
AG VEndor Supply Management - 3
AG Air Operations Tools and Equipment Knowledge -2
AUTO Labor Relations Knowledge -3
AUTO Budget Management -3
AUTO Mechanical Knowledge -3
AUTO Applies Service, Product, and Customer Technology Knowledge    -3
AUTO Automotive Engineering Knowledge -1
Run Code Online (Sandbox Code Playgroud)

即使相同的CMX_DSC_TE重复完全相同的分数,我也只需要列出其中一个.

Tar*_*ryn 5

你对一个群体的要求并不十分清楚,但听起来你希望jsc_gaps每个群体的回报最差job_function.如果我正确地解释了这一点,那么你应该能够使用row_number()和分区数据并通过以下方式job_function对其进行排序jsc_gap:

select 
  Job_Function, 
  CMX_DSC_TE, 
  JSC_Gap
from
(
  select 
    Job_Function, 
    CMX_DSC_TE, 
    MGR_ANW_CD_Num - DES_LVL_NR_Num AS JSC_Gap,
    row_number() over(partition by job_function
                      order by MGR_ANW_CD_Num - DES_LVL_NR_Num) seq
  FROM  dbo.AC_GLN_Project_JSC
) d
where seq <= 5
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

根据您的编辑,您应该能够使用:

;with cte as 
(
  select 
    Job_Function, 
    CMX_DSC_TE, 
    JSC_Gap = MGR_ANW_CD_Num - DES_LVL_NR_Num,
    row_number() over(partition by Job_Function, CMX_DSC_TE
                      order by MGR_ANW_CD_Num - DES_LVL_NR_Num, CMX_DSC_TE) seq
  FROM  dbo.AC_GLN_Project_JSC
)
select Job_Function, 
    CMX_DSC_TE, 
    JSC_Gap
from
(
  select Job_Function, 
    CMX_DSC_TE, 
    JSC_Gap,
    row_number() over(partition by Job_Function
                      order by JSC_Gap, CMX_DSC_TE) rn
  from cte
  where seq = 1
) d
where rn <= 5;
Run Code Online (Sandbox Code Playgroud)

演示