检索员工的主要和次要职能

时间:2019-08-08 11:48:39

标签: sql sql-server

我的表Employee,Function和Company之间的关系位于[Employee_Scope]中 在Employee_Scope中,有一个名为[SortOrder]的订单列。 主要职能是指特定员工在SortOrder != NULL and SortOrder = MIN(SortOrder)范围内的职能。 剩下的就是次要功能。

示例:

enter image description here

主要功能ID为“ 1”。
次要functionId为54。
该函数本身可以在[Employee_Function]表中找到。

我已经通过以下查询提取了所有功能:

SELECT [le].[EmployeeId], [le].[FunctionId], ROW_NUMBER() OVER(PARTITION BY [le].[EmployeeId] ORDER BY [le].[SortOrder] ASC) AS [RealOrder] 
        FROM (
              SELECT [e].[EmployeeId], [es].[FunctionId], ISNULL([es].[SortOrder], 0) AS [SortOrder]
         FROM [dbo].[Employee] [e] 
                 INNER JOIN [dbo].[Employee_Scope] AS [es]  ON [es].[EmployeeId] = [e].[EmployeeId]
                  WHERE es.SortOrder != NULL
                    HAVING es.SortOrder !=MIN(es.SortOrder) ) [le]

上一个查询的输出:

enter image description here

现在我需要分别获取每位员工的主要职能和次要职能,因此我尝试了以下方法来获得主要职能:

SELECT [le].[EmployeeId], [le].[FunctionId], ROW_NUMBER() OVER(PARTITION BY [le].[EmployeeId] ORDER BY [le].[SortOrder] ASC) AS [RealOrder] 
                     FROM (
          SELECT [e].[EmployeeId], [es].[FunctionId], ISNULL([es].[SortOrder], 0) AS [SortOrder]
         FROM [dbo].[Employee] [e] 
         INNER JOIN [dbo].[Employee_Scope] AS [es]  ON [es].[EmployeeId] = [e].[EmployeeId]
        WHERE es.SortOrder = (SELECT MIN(es1.SortOrder) FROM Employee_Scope es1)
                 ) [le] 

预期输出:

对于EmployeeId = 5205

EmployeeId FunctionId(Main) CompanyId SortOrder
5205       1                20        1

EmployeeId FunctionId(Secondary) CompanyId SortOrder
5205       1                     50        30
5205       54                    154       60

1 个答案:

答案 0 :(得分:2)

我正在阅读此书,并将其视为逻辑:

主要功能:

where sortorder = 0

对于次要对象:

where sortorder > 0

我想念什么吗?

编辑:

如果希望最小值作为“主”行,则:

select t.*
from (select t.*,
             row_number() over (partition by employeeid order by sortorder) as seqnum
      from t
     ) t

然后根据需要使用where seqnum = 1where seqnum > 1