0

我有以下查询,我需要为每个工作组选择前 3 个培训。所以我需要每个工作组返回他们的 3 个最高培训。到目前为止的代码是

SELECT Mgmt_Lvl.MGMT_LVL, Book6.[Item ID], Book6.Description, Count(Book6.[User ID]) AS [CountOfUser ID]
FROM Mgmt_Lvl INNER JOIN ((Book6 INNER JOIN O896IA_VEMPPRSA ON Book6.[User ID] = O896IA_VEMPPRSA.SYS_EMP_ID_NR) INNER JOIN O867IA_VPJOBCO ON O896IA_VEMPPRSA.JOB_CLS_CD = O867IA_VPJOBCO.JOB_CLS_CD) ON Mgmt_Lvl.JOB_GRP_CD = O867IA_VPJOBCO.JOB_GRP_CD
GROUP BY Mgmt_Lvl.MGMT_LVL, Book6.[Item ID], Book6.Description
ORDER BY Count(Book6.[User ID]) DESC;

Count(Book6.[User ID]) AS [CountOfUser ID]

是我需要前 3 名的领域

4

1 回答 1

0

What you want is a common table expression (CTE) with the row_number() function.

It's hard to get a grasp of the field you want counted by referencing it as "job group." I don't see a field by that name. That being said, here is a basic example of the query you want. If you replace the fields appropriately, it should give you the desired output.

WITH CTE_NAME (COL1, COL2, JOB_GROUP, ROWNUM)
AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY JOB_GROUP ORDER BY JOB_GROUP)
      , COL1
      , COL3
      , JOB_GROUP
FROM TABLE A
JOIN TABLE B
ON A.KEY = B.KEY
)

SELECT * 
FROM CTE_NAME
WHERE ROWNUM IN ('1','2','3')
ORDER BY JOB_GROUP

Explanation: "PARTITION BY" separates your data into groups based on the field you enter. When you add the ROW_NUMBER() function, you are assigning a unique row number for each record within the grouping you created. So, by selecting ROWNUMs '1', '2', '3', you essentially select the TOP 3 rows for each group. Just be sure you ORDER BY the correct field in your CTE expression.

于 2013-10-30T18:30:57.483 回答