SQL用于查找月内的员工休假天数

时间:2017-09-05 08:26:29

标签: sql sql-server date

当我选择开始日期= 2017-02-01并离开日期= 2017-02-28时,我想显示员工离职表格。输出显示如此

EmployeeID Leave_Start_Date Leave_End-Date
--------- ----------------- ---------------
1         2017-01-29        2017-02-01
2         2017-02-01        2017-02-02

我希望输出符合

EmployeeID Leave_Start_Date Leave_End-Date
--------- ----------------- ---------------
1         2017-02-01        2017-02-01
2         2017-02-01        2017-02-02

我像那样编写查询

DECLARE @StartDate  DATE
,       @EndDate    DATE            
SET     @StartDate='2017-02-01'
SET     @EndDate='2017-02-28'
SELECT      *
FROM        Employee_Leave
WHERE       Leave_Start_Date BETWEEN @StartDate AND @EndDate
OR          Leave_End_Date  BETWEEN @StartDate  AND @EndDate
ORDER BY    Leave_Start_Date;

2 个答案:

答案 0 :(得分:1)

您可以使用以下查询:

DECLARE @StartDate  DATE
,       @EndDate    DATE            
SET     @StartDate='2017-02-01'
SET     @EndDate='2017-02-28'

SELECT      EmployeeID,
            CASE 
               WHEN Leave_Start_Date < @StartDate THEN @StartDate
               ELSE Leave_Start_Date 
            END AS Leave_Start_Date,
            CASE 
               WHEN Leave_End_Date > @EndDate THEN @EndDate
               ELSE Leave_End_Date 
            END AS Leave_End_Date          
FROM        Employee_Leave 
WHERE       Leave_Start_Date <= @EndDate AND
            Leave_End_Date >= @StartDate
ORDER BY    Leave_Start_Date;

查询截断[Leave_Start_Date, Leave_End_Date]间隔以匹配[@StartDate, @EndDate]间隔。

Demo here

答案 1 :(得分:0)

我建议使用>=<=运算符,并将(列名)转换为日期格式

以下示例:

SELECT * FROM sys.sys_config where cast(set_time as date) <= "2016-09-25" and cast(set_time as date) >= "2016-09-01"