SQL Query从同一个表中返回1行或更多行的余额总和

时间:2016-08-05 07:23:09

标签: sql sql-server sql-server-2012

我在stackoverflow上的第一篇文章 - 希望你能帮助这个新手!

我要求在SQL Server 2012的同一个表中返回1行或更多行的休假余额总和。结果集必须按EmployeeID和BalanceStartDate分组。在某些情况下,员工有多个LeaveType,并且有些员工只有一个休假类型。

如果BalanceStartDate和Employee只存在一个LeaveType,则返回LeaveBalance。如果存在多个,则将LeaveBalance与LeaveType相加并返回1结果。

表格中的我的源数据如下:

EmployeeID    BalanceStartDate    LeaveCategory    LeaveType    LeaveBalance
----------    ----------------    -------------    ---------    ------------
1             01-JAN-2016         ANNUAL           MANDATORY    2
1             01-JAN-2016         ANNUAL           NON-MAN      3
1             01-JAN-2015         ANNUAL           MANDATORY    5
1             01-JAN-2015         ANNUAL           NON-MAN      2
2             01-JAN-2016         ANNUAL           MANDATORY    6
2             01-JAN-2015         ANNUAL           MANDATORY    3
2             01-JAN-2014         ANNUAL           MANDATORY    1
2             01-JAN-2014         ANNUAL           NON-MAN      1

我的预期结果集是:

EmployeeID    BalanceStartDate    LeaveCategory    Sum
----------    ----------------    -------------    ---
1             01-JAN-2016         ANNUAL           5
1             01-JAN-2015         ANNUAL           7
2             01-JAN-2016         ANNUAL           6
2             01-JAN-2015         ANNUAL           3
2             01-JAN-2014         ANNUAL           2

因此,对于每个“年份”,我们应该有一个唯一的行来总结LeaveTypes之间的平衡(如果存在多个)。如果只有1个LeaveType,则只返回休假余额。

我写了以下内容(几乎就在那里),但它排除了只存在1个LeaveType的行,并且仍然在一年内返回2行:

select A.LeaveBalance + B.LeaveBalance as 'Sum', A.EmployeeID
From
Table A
Inner Join Table B On A.EmployeeID = B.EmployeeID 
AND A.LeaveCategory = 'ANNUAL'
AND A.LeaveCategory = B.LeaveCategory 
AND A.BalanceStartDate = '01-JAN-2016'
AND A.BalanceStartDate = B.BalanceStartDate 
AND A.EmployeeID = '12345' 
AND A.LeaveType <> B.LeaveType

我希望这是足够的信息? 任何帮助将不胜感激。请原谅我的新手代码!

3 个答案:

答案 0 :(得分:0)

您应该使用SUM function

试试这个:

SELECT EmployeeID, BalanceStartDate, LeaveCategory, LeaveType, SUM(LeaveBalance) As SumOfLeaves
FROM YourTable
GROUP BY EmployeeID, BalanceStartDate, LeaveCategory, LeaveType

答案 1 :(得分:0)

试试这个,

SELECT 
    A.EmployeeID,
    A.LeaveCategory,
    A.BalanceStartDate,
    SUM(A.LeaveBalance) AS TotalLeave
FROM
Table A
WHERE A.LeaveCategory = 'ANNUAL'
AND A.EmployeeID = '12345' 
GROUP BY
    A.EmployeeID,
    A.LeaveCategory,
    A.BalanceStartDate

答案 2 :(得分:0)

select  
    EMPLOYEEID  
    ,BALANCESTARTDATE  
    ,LEAVECATEGORY  
    ,SUM( LEAVEBALANCE ) as sum  
from  
    EMPLOYEES  
group by  
    EMPLOYEEID  
    ,BALANCESTARTDATE  
    ,LEAVECATEGORY  
order by  
    EMPLOYEEID  
   ,BALANCESTARTDATE desc;  

它会按预期给出结果。