如何找到前 5 行?

问题描述 投票:0回答:1

> Hi,
> 
> I have an ASP.NET Core MVC app that contains two entities: Employee
> and Task. The relationship between these two entities is One-to-many.
> The information stored for an employee is the full name, email, phone
> number, date of birth, and monthly salary. The task consists of a
> title, description, assignee(the employee assigned to work on it), and
> a due date. I need to display the 5 employees who completed the
> largest number of tasks in the past month.

我试过以下方法:

public async Task<IActionResult> Display()
        {
            int current_month = DateTime.Now.Month;

            var employees = _context.Employees.Include(t => t.EmployeeTasks).OrderByDescending(x => x.EmployeeTasks.Count(x => x.DueDate.Month == current_month - 1)).Take(5);

            return View(employees);
        }

这个查询不正常,好像不识别条件

DueDate.Month == current_month - 1

有人知道如何更正给定的查询吗?

c# sql-server entity-framework asp.net-core-mvc
1个回答
0
投票

使用 current_month 变量按截止日期过滤任务可能会导致查询问题。如果当前月份是一月(值为 1),则从 current_month 中减去 1 可能不会总是产生预期的结果。

要解决此问题,您可以修改查询以使用 DateTime 属性月和年根据截止日期过滤任务。使用以下查询,您可以过滤上个月到期的任务

// Get the start and end dates of the previous month
    var currentDate = DateTime.Now;
    var startDate = new DateTime(currentDate.Year, currentDate.Month, 1).AddMonths(-1);
    var endDate = startDate.AddMonths(1).AddDays(-1);

    // Retrieve the top 5 employees who completed the most tasks in the previous month
    var employees = await _context.Employees
        .Include(e => e.EmployeeTasks)
        .OrderByDescending(e => e.EmployeeTasks.Count(t => t.DueDate >= startDate && t.DueDate <= endDate))
        .Take(5)
        .ToListAsync();
© www.soinside.com 2019 - 2024. All rights reserved.