我正在尝试计算不同年份的持续时间,其中:
startdate enddate duration (days)
2016-09-20 2018-09-20 730
如果我希望将以下结果作为每年的持续时间, 以年为列名,结果为天:
2016 = 103天-2017 = 365天-2018 = 263天
除了使用DATEDIFF并输入每年的结束日期外,我找不到特定的解决方案,但这无法计算下一年的剩余天数。谁能帮助我找到MySQL解决方案?
答案 0 :(得分:0)
假设(希望)您有一个数字表,则可以进行以下计算:
SELECT startdate,
enddate,
number AS year_num,
DATEDIFF(
LEAST(DATE(CONCAT(number, '-12-31')), enddate),
GREATEST(DATE(CONCAT(number, '-01-01')), startdate)
) + 1 AS num_days
FROM t
INNER JOIN (
SELECT 2010 AS number UNION ALL
SELECT 2011 UNION ALL
SELECT 2012 UNION ALL
SELECT 2013 UNION ALL
SELECT 2014 UNION ALL
SELECT 2015 UNION ALL
SELECT 2016 UNION ALL
SELECT 2017 UNION ALL
SELECT 2018 UNION ALL
SELECT 2019
) AS numbers ON number BETWEEN YEAR(startdate) AND YEAR(enddate)