SUM函数SQL Server

时间:2018-08-08 03:36:18

标签: sql sql-server sum

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetJobInfo]
AS
BEGIN
    SELECT 
        dbo.EmployeeJobs.EmployeeId, dbo.EmployeeJobs.ComputerCodeId, 
        FirstName, LastName
    FROM 
        dbo.Employees
    INNER JOIN 
        dbo.EmployeeJobs ON dbo.Employees.EmployeeId = dbo.EmployeeJobs.EmployeeId 
    WHERE
        dbo.EmployeeJobs.ComputerCodeId IN (7,8,9,13,14,15,16,17,18,19,22)
END

这是我当前的存储过程,到目前为止,所有功能都可以正常运行。我的employeejobs表有一个名为RegularHours的属性。我需要完成返回的工作,对于每位员工,我需要从所有工作中总计regularHours。我在看求和函数,但无法正常工作。

有人可以指出正确的方向吗?在继续之前,我需要创建一个数组属性并将所有作业设置为该属性吗?

2 个答案:

答案 0 :(得分:0)

我认为您正在寻找类似的东西

Select E.EmployeeId, EJ.ComputerCodeId, E.FirstName, E.LastName, SUM(EJ.RegularHours) as RegularHours
From dbo.Employees E
    INNER JOIN dbo.EmployeeJobs EJ ON E.EmployeeId = EJ.EmployeeId 
Where EJ.ComputerCodeId in (7,8,9,13,14,15,16,17,18,19,22)
Group By E.EmployeeId, E.FirstName, E.LastName, EJ.ComputerCodeId

答案 1 :(得分:0)

使用子查询。这将返回所有工作的员工总时数,而不仅是结果上的工作:

Select E.EmployeeId, EJ.ComputerCodeId, E.FirstName, E.LastName, 
       (Select Sum(H.RegularHours) 
        From EmployeeJobs H 
        Where H.EmployeeId = E.EmployeeID and
              H.ComputerCodeId in (7,8,9,13,14,15,16,17,18,19,22)) as RegularHours
From dbo.Employees E
    Inner Join dbo.EmployeeJobs EJ on E.EmployeeId = EJ.EmployeeId 
Where EJ.ComputerCodeId in (7,8,9,13,14,15,16,17,18,19,22)

子查询的语法很简单,但是效率不高。您可以使用CTE(公用表表达式)优化其执行:

with H as (
  Select EmployeeID, Sum(RegularHours) as RegularHours
  From EmployeeJobs
  Where ComputerCodeId in (7,8,9,13,14,15,16,17,18,19,22)
)
Select E.EmployeeId, EJ.ComputerCodeId, E.FirstName, E.LastName, H.RegularHours
From dbo.Employees E
    Inner Join dbo.EmployeeJobs EJ on E.EmployeeId = EJ.EmployeeId 
    Inner Join H on H.EmployeeId = E.EmployeeId 
Where EJ.ComputerCodeId in (7,8,9,13,14,15,16,17,18,19,22)