计算每月休假余额

时间:2018-01-31 13:57:41

标签: sql-server

我的表结构正在获取有关员工的休假详细信息。我想计算一个员工每个月有多少叶子以及休假类型。

CREATE TABLE Employee
(
EmpID Int Primary Key,
Name Varchar(25)
);

CREATE TABLE LeaveBalance
(
BalanceID Int Primary Key,
Balance Int,
EmpID Int FOREIGN KEY REFERENCES Employee(EmpID)
);

CREATE TABLE Leave
(
ID Int,
LeaveType Varchar(25),
AppliedOn Date,
ApprovedOn Date,
EmpID Int FOREIGN KEY REFERENCES Employee(EmpID),
BalanceID Int FOREIGN KEY REFERENCES LeaveBalance(BalanceID)

);



INSERT INTO Employee VALUES (1, 'Erick')
INSERT INTO Employee VALUES (2, 'John')


INSERT INTO LeaveBalance VALUES (1, 25, 1)
INSERT INTO LeaveBalance VALUES (2, 15, 2)

INSERT INTO Leave VALUES (1, 'Sick Leave', '2017-12-21', '2017-12-22', 1, 1)
INSERT INTO Leave VALUES (2, 'Casual Leave', '2017-12-26', '2017-12-26', 1, 1)
INSERT INTO Leave VALUES (3, 'Sick Leave', '2018-01-11', '2018-01-11', 1, 1)
INSERT INTO Leave VALUES (4, 'Casual Leave', '2017-12-26', '2017-12-26', 2, 2)
INSERT INTO Leave VALUES (5, 'Earned Leave', '2018-01-11', '2018-01-11', 2, 2)

1 个答案:

答案 0 :(得分:2)

它应该如此简单(假设您使用AppliedOn的日期而不是Date ApprovedOn):

SELECT 
      EmpID
    , LeaveType 
    , YEAR(AppliedOn)   AS [Year]
    , MONTH(AppliedOn)  AS [Month]
    , Count(*)          AS [LeaveTaken]
FROM #Leave
GROUP BY EmpID
    , LeaveType 
    , YEAR(AppliedOn)   
    , MONTH(AppliedOn)