计算特定年份的sql中的日期差异
Posted
技术标签:
【中文标题】计算特定年份的sql中的日期差异【英文标题】:Calculate date difference in sql for specific year 【发布时间】:2015-07-23 11:11:44 【问题描述】:我有两个日期,比如 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
谢谢
【问题讨论】:
【参考方案1】:您需要修复 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
【讨论】:
感谢 Gordon,这非常适合我所追求的。【参考方案2】:使它成为AND
条件,而不是像
WHERE
((YEAR(start_date) = :year) AND (YEAR(end_date) = :year))
【讨论】:
以上是关于计算特定年份的sql中的日期差异的主要内容,如果未能解决你的问题,请参考以下文章