最近我一直在开发休假管理系统。在这个应用程序中,我需要一份月度员工休假声明中的报告。
所以这是我的样本表:
Employee Id application Date Start Date End Date
20130002 14-Mar-2016 16-Mar-2016 17-Mar-2016
20130012 15-Mar-2016 29-Mar-2016 2-Apr-2016
20130003 14-Mar-2016 15-Mar-2016 16-Mar-2016
20130005 10-Mar-2016 24-Mar-2016 24-Mar-2016
20130002 10-Mar-2016 20-Mar-2016 25-Mar-2016
20130006 13-Mar-2016 8-Mar-2016 17-Mar-2016
20130001 14-Mar-2016 4-Apr-2016 24-Apr-2016
20130003 15-Mar-2016 16-May-2016 18-May-2016
20130011 10-Mar-2016 7-Jun-2016 7-Jun-2016

现在我需要一份报告,我可以按月报告这份报告。假设我只需要March的数据,如下所示:
<pre>
Employee Id application Date Start Date End Date
20130002 14-Mar-2016 16-Mar-2016 17-Mar-2016
20130012 15-Mar-2016 29-Mar-2016 31-Mar-2016
20130003 14-Mar-2016 15-Mar-2016 16-Mar-2016
20130005 10-Mar-2016 24-Mar-2016 24-Mar-2016
20130002 10-Mar-2016 20-Mar-2016 25-Mar-2016
20130006 13-Mar-2016 8-Mar-2016 17-Mar-2016
</pre>
&#13;
我如何通过PL / SQL或任何SQL语言实现这一目标?
答案 0 :(得分:1)
假设日期的时间部分设置为00:00:00
,那么:
SELECT EmployeeId,
application_date,
GREATEST( start_date, DATE '2016-03-01' ) AS start_date,
LEAST( end_date, DATE '2016-03-31' ) AS end_date
FROM table_name
WHERE Start_date <= DATE '2016-03-31'
AND end_date >= DATE '2016-03-01'
您可以使用绑定变量替换硬编码日期,如下所示:
SELECT EmployeeId,
application_date,
GREATEST( start_date, :month_start ) AS start_date,
LEAST( end_date, LAST_DAY( :month_start ) ) AS end_date
FROM table_name
WHERE Start_date <= LAST_DAY( :month_start )
AND end_date >= :month_start
如果你有时间成分,那么:
SELECT EmployeeId,
application_date,
GREATEST( start_date, :month_start ) AS start_date,
LEAST( end_date, :month_start + INTERVAL '1' MONTH - INTERVAL '1' SECOND )
AS end_date
FROM table_name
WHERE Start_date < :month_start + INTERVAL '1' MONTH
AND end_date >= :month_start
答案 1 :(得分:0)
条件应为
WHERE StartDate>='01-Mar-2016' and EndDate <'01-Apr-2016'
答案 2 :(得分:0)
这适用于SQL Server
SELECT *
FROM Leaves
WHERE MONTH(StartDate) <= 4 and Month(EndDate) >= 4
对于Oracle
SELECT *
FROM Leaves
WHERE EXTRACT(month FROM StartDate) <= 4 and EXTRACT(month FROM EndDate) >= 4
答案 3 :(得分:0)
您可以使用所需月份的参数格式&#39; YYYYMM&#39; (2016年3月:&#39; 201603&#39;)
然后where子句将是:
where parameter = to_char(start_date,'yyyymm')
or parameter = to_char(end_date,'yyyymm')
如果请假可能超过一个月,那么您还需要检查参数是否在开始日期和结束日期之间。
..
or parameter between to_char(start_date,'yyyymm') and to_char(end_date,'yyyymm')
要在报告中显示正确的日期,您可以使用CASE语句结合first_day和last_day函数来显示该月的第一天和最后一天。 (此处parameter_date是DATE所需的月份,而不是VARCHAR2)
CASE
WHEN start_date < first_day(parameter_date) THEN first_day(parameter_date)
ELSE start_date
END as start_Date,
CASE
WHEN end_date > last_day(parameter_date) THEN last_day(parameter_date)
ELSE end_date
END as end_Date