计算特定年份的sql中的日期差异

时间:2015-07-23 11:11:45

标签: mysql sql

我有两个日期,比如start_date是20141215和end_date = 20150115。我想使用SQL DATEDIFF来计算我将在查询中指定的2015年内的日期。这是我写的当前SQL:

SELECT COUNT(leave_id), 
    sum(case when leave_status = 1 then 1 else 0 end) pending, 
    sum(case when leave_status = 2 then 1 else 0 end) declined, 
    sum(case when leave_status = 3 then 1 else 0 end) approved,
    sum(case when leave_status = 4 then 1 else 0 end) rostered,
    SUM(DATEDIFF(end_date, start_date)+1) as datetotals
    FROM employee_leave WHERE 
    ((YEAR(start_date) = :year) OR (YEAR(end_date) = :year)) 
    AND employee_id = :emp_id

由于

2 个答案:

答案 0 :(得分:0)

您需要修复datediff()以仅考虑一年中的日期。我认为这样做你想要的:

SELECT COUNT(leave_id), 
       sum(case when leave_status = 1 then 1 else 0 end) pending, 
       sum(case when leave_status = 2 then 1 else 0 end) declined, 
       sum(case when leave_status = 3 then 1 else 0 end) approved,
       sum(case when leave_status = 4 then 1 else 0 end) rostered,
       SUM(DATEDIFF(least(end_date, date(concat_ws('-', :year, 12, 31))),
                    greatest(start_date, date(concat_ws('-', :year, 1, 1)))
                   ) + 1) as datetotals
FROM employee_leave 
WHERE ((YEAR(start_date) = :year) OR (YEAR(end_date) = :year)) AND
      employee_id = :emp_id

答案 1 :(得分:0)

将其设为AND条件而非

WHERE 
    ((YEAR(start_date) = :year) AND (YEAR(end_date) = :year))