-1

我在 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

该表如下所示:(这是一个较小的版本)

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

我需要它看起来像:

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

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

4

1 回答 1

5

您对一个组的要求并不完全清楚,但听起来您希望每个组都返回 5 个最差jsc_gapsjob_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

请参阅带有演示的 SQL Fiddle

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

;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;

演示

于 2013-09-05T17:51:08.910 回答