在日期范围之间计数

时间:2015-08-20 10:56:33

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

我有很多员工假期记录,显示假期开始和结束日期。我需要弄清楚每个员工在两个日期之间花了多少假期,即2015-01-01 00:00:002015-02-01 00:00:00

我如何处理假期在该范围之前开始或在该范围之后结束的假期?

  • 例如,如果employee 1取消2015-01-102015-01-15,那就可以作为5天假期

  • 但如果employee 2取消2015-12-252015-01-05,那应该算作5天假期

  • 另一方也是如此,即如果employee 3取消2015-01-252015-02-05,则该计数应仅计为5天假期

4 个答案:

答案 0 :(得分:1)

假设您的员工假期表如下所示:

CREATE TABLE EmployeeHoliday (
    EmployeeId INT,
    HolidayStart DATETIME,
    HolidayEnd DATETIME
)

以下查询返回两个指定日期(变量)之间每位员工的天数:

DECLARE @CountFromDate AS DATETIME = '2015-01-01'
DECLARE @CountToDate AS DATETIME = '2015-02-01'

SELECT EmployeeId,
    SUM(DATEDIFF(DAY,
        CASE WHEN @CountFromDate < HolidayStart THEN HolidayStart ELSE @CountFromDate END,
        CASE WHEN @CountToDate > HolidayEnd THEN HolidayEnd ELSE @CountToDate END
        )
    ) AS HolidaysHeld
FROM EmployeeHoliday
GROUP BY EmployeeId

如果您不希望此查询输出仅在指定时间间隔之外有假期的员工,请在查询的WHERE部分之前包含以下GROUP BY - 子句:

WHERE HolidayStart <= @CountToDate AND HolidayEnd >= @CountFromDate

答案 1 :(得分:1)

您使用日期逻辑。其他数据库具有least()greatest()功能来帮助解决此问题。在SQL Server中,您可以使用更复杂的case语句。结果是这样的:

select h.employee_id,
       sum(datediff(day, 
                    (case when h.start < @StartDate then @StartDate else h.start end),
                    (case when h.end > @EndDate then @EndDate else h.end end)
                   )
          ) as DaysOnHoliday
from holidays h
where h.start <= @EndDate and h.end >= @StartDate
group by h.employee_id

答案 2 :(得分:0)

declare @datebeg datetime = '20150101', @dateend datetime = '20150201'

select e.employeeid, sum(datediff(day, case when @datebeg < h.datebeg then h.datebeg else @datebeg end,
                                       case when @dateend > h.dateend then h.dateend else @dateend end))
from holiday h 
where @datebeg <= h.dateend and @dateend >= h.datebeg
group by h.employeeid

答案 3 :(得分:0)

你尝试从tablename中选择date date1-date2;