获取所有带有最小值的项目SQL Server

时间:2019-03-05 13:11:33

标签: sql sql-server

这是桌子的样子:

----------------------------------
   EmployeeId      Tasks_Count
   1               1
   2               1
   3               2
   4               1
   5               3

我需要一个查询来获取所有具有最少任务数的员工。结果应该是这样的:

---------------
   EmployeeId   
   1               
   2               
   4

问题是我使用子查询来计数任务。这是我的代码

SELECT *
FROM (SELECT EmployeeId,
             COUNT(*) AS Tasks_count
      FROM Tasks
      INNER JOIN Status ON Tasks.StatusId=Status.Id
      WHERE Status.Name != 'Closed'
      GROUP BY EmployeeId
      ORDER BY Tasks_count DESC) AS Employee_not_closed
WHERE Tasks_count IN (SELECT MIN(Tasks_count) 
                      FROM Employee_not_closed)

5 个答案:

答案 0 :(得分:3)

使用FETCH FIRST WITH TIES

select EmployeeId
from tablename
order by Tasks_Count
fetch first 1 row with ties

答案 1 :(得分:1)

您可以在下面尝试-

select * from tablename
where Tasks_Count in (select min(Tasks_Count) from tablename)

答案 2 :(得分:1)

也可以使用RANK()函数,如下所示。

;with cte as
(
   select Employeeid, rank() over( order by Tasks_Count) rn
   from @table
)
select * from cte where rn=1

答案 3 :(得分:1)

您可以使用下面的代码,我已经测试了该代码及其正常工作。

select EmployeeId from StackOverFlow_3 where Tasks_Count in(select min(Tasks_Count) from StackOverFlow_3)

答案 4 :(得分:0)

您可以在子查询上使用联接

    select m.EmployeeId 
    from my_table  m
    inner join  
    (
        select min(task_count) min_task
        from my_table 
    ) t  on t.min_task = m.task_count