想要在mysql中计算月假天数

时间:2016-03-30 06:32:50

标签: mysql sql

情况是员工申请休假:从日期是“2016-03-30”,到日期是“2016-04-02”所以输出将是“在第3个月休假日应该是2”和“在4日月假天数应为1“。 我有桌子:

UserID          FromDate      ToDate     LeaveDuration
------------------------------------------------------
0001            20/03/2016    21/03/2016       1
0001            30/03/2016    02/04/2016       2

在第2个记录2天应考虑在第3个月,1个月应在第4个月考虑。 我试过下面的查询:

select sum(datediff(ToDate,FromDate)) as Total
from wp_ag_assign_leave
where UserId=18
  and LeaveType="Carry Forward Leave"
  and (EXTRACT(MONTH FROM CURDATE())=EXTRACT(MONTH FROM FromDate)
  OR EXTRACT(MONTH FROM CURDATE())=EXTRACT(MONTH FROM ToDate))

请帮我解决一下

1 个答案:

答案 0 :(得分:0)

你可能想要确定某些日期,例如date_add,但这就是我所做的:

select month,
       sum(duration) as 'LeaveDays'       
from (
  select if(month(FromDate)=month(ToDate),month(FromDate),'other') as 'month',
        if(month(FromDate)=month(ToDate),datediff(Todate, FromDate),'other')  as 'duration'
 from wp_ag_assign_leave
 UNION   
 select  if(month(FromDate)!=month(ToDate),month(FromDate),'other') as 'month',
           if(month(FromDate)!=month(ToDate),datediff(last_day(FromDate),FromDate),'other') as 'duration'
 from wp_ag_assign_leave
 UNION
 select  if(month(FromDate)!=month(ToDate),month(ToDate),'other') as 'month',
           if(month(FromDate)!=month(ToDate),dateDiff(ToDate,last_day(FromDate)),'other') as 'duration'
 from wp_ag_assign_leave
) as parseMonths
where month!='other'
group by month
order by month;

SELECT声明中的3 UNION: - 1日期是在同一个月,简单的区别 - 2日期不在同一个月:第一个月的部分 - 2日期不在同一个月:第二个月的部分