asp.net mvc5,raw sql:使用聚合函数

时间:2017-10-05 00:56:54

标签: sql-server asp.net-mvc linq

我正在使用ASP.NET MVC,EF和SQL Server 2014。

我想生成一个视图,该视图显示员工身份的员工总休病假和年假。我发现LINQ查询非常复杂,我不知道如何在Asp.net MVC中使用它。我为此编写了一个控制器,现在我不知道如何在视图中显示这些数据。

请帮我解决这个问题。如果有更好的方法,或者我犯了错误,请告诉我。

SQL查询如下:

SELECT 
    [EmployeeId], SUM(AssignedLeaveDay) AS Total_Annual_Leave    
FROM 
    AssignLeaves 
WHERE
    [EmployeeId] = 1 AND LeaveTypeId = 4
GROUP BY 
    [EmployeeId]

SELECT 
    [EmployeeId], SUM(AssignedLeaveDay) AS Total_Sick_Leave    
FROM 
    AssignLeaves 
WHERE
   [EmployeeId] = 1 AND LeaveTypeId = 5
GROUP BY 
   [EmployeeId]

enter image description here

1 个答案:

答案 0 :(得分:0)

//控制器侧
 var Data =来自AssignLeaves.Where中的数据(s => s.EmployeeId == 1&& s.LeaveTypeId == 4)
                                   按data.EmployeeId分组数据到g
                                   选择新的                                    {
                                       EmployeeId = g.Key,
                                       Total_Annual_Leave = g.Sum(x => x.AssignedLeaveDay)
                                   };

var SickLeaveData =来自AssignLeaves.Where中的数据(s => s.EmployeeId == 1&& s.LeaveTypeId == 5)
                                   按data.EmployeeId分组数据到g
                                   选择新的                                    {
                                       EmployeeId = g.Key,
                                          Total_Sick_Leave = g.Sum(x =>  x.AssignedLeaveDay)
                                   };

您可获得年度总休假:Data.FirstOrDefault()。Total_Annual_Leave;
你得到Total_Sick_Leave:SickLeaveData.FirstOrDefault()。Total_Sick_Leave;