计算SQL Server中一个月内Employee采用的叶数

时间:2015-08-19 09:22:38

标签: sql sql-server sql-server-2008

如何在SQL Server中计算一个月内Employee采用的叶子数量?

Empid   Leaveid   Fromdate    Todate      No of days
100     L1        2008-05-10  2008-05-13  3
100     L2        2008-05-20  2008-05-21  1
100     L3        2008-05-25  2008-06-05  12
100     L4        2009-01-20  2009-01-22  2
100     L5        2009-02-14  2009-02-20  6
100     L6        2009-02-28  2009-02-28  1

2 个答案:

答案 0 :(得分:2)

使用SUMGROUP BY

SELECT Empid, SUM([No of Days]) AS Days
FROM leavetable
GROUP BY Empid

在此处GROUP BYSUM了解更多信息。

这会给你:

Empid Days
100   25

或者,如果您的意思是计算员工不使用的次数Count

SELECT Empid, Count(Leaveid) AS LeaveTotal 
FROM leavetable
GROUP BY Empid

在此处阅读更多COUNT

这会给你:

Empid LeaveTotal
100   6

答案 1 :(得分:0)

CREATE TABLE #EmpLeave (EmpId INT, LeaveID VARCHAR(5), FromDate Date, Todate Date, NoOfDays INT)
INSERT INTO #EmpLeave VALUES
(100,     'L1',        '2008-05-10',  '2008-05-13',  4),
(100,     'L2',        '2008-05-20',  '2008-05-21',  2),
(100,     'L3',        '2008-05-25',  '2008-06-05',  12),
(100,     'L4',        '2009-01-20',  '2009-01-22',  3),
(100,     'L5',        '2009-02-14',  '2009-02-20',  7),
(100,     'L6',        '2009-02-28',  '2009-02-28',  1)


;With CTE_leave AS (
select * from #EmpLeave where Month(FromDate) <> Month(ToDate) )


SELECT a.EMPID,DATENAME(MONTH,FromDate ) Month ,SUM(a.LeaveCount) LeaveTaken
FROM 
(

SELECT C.EMPID,C.LeaveID, C.FromDate, DATEDIFF(DD,C.FromDate,EOMonth(FromDate) ) + 1 LeaveCount
FROM CTE_Leave C
UNION
SELECT C.EMPID, C.LeaveID, DATEADD(DD,1, EOMonth(FromDate)) fromDate, DATEDIFF(DD,DATEADD(DD,1, EOMonth(FromDate)), C.ToDate ) + 1 LeaveCount
FROM CTE_Leave C
UNION
SELECT EMPID, LeaveID, FromDate,  DATEDIFF(DD, FromDate, Todate) + 1 LeaveCount FROM #EmpLeave where Month(FromDate) = Month(ToDate) 
) a
group by a.EMPID,  DATENAME(MONTH,FromDate )

@Anchalose找到以上可能的解决方案。让我们来解决您的疑问。 请在发布查询时发布架构详细信息以及所需结果,这将有助于我们更好地理解问题。

@Matt,请不要使用cuss字样,并尝试按照要求发布解决方案。