如何在我的案例陈述中添加 "range of years"

How do I add in a "range of years" to my Case Statement

如何在下面的案例陈述中添加 "range of years"?我只需要修复 "INTERVAL 6 YEAR" & "INTERVAL 5 YEAR" 标准。

这是我需要建模的标准:

如果1~5年,那么11

如果6~10年,那么14

如果 11+ 岁,则 18

CASE WHEN hiredate < DATE_SUB(NOW(),INTERVAL 11 YEAR)
 THEN '18'
 WHEN hiredate < DATE_SUB(NOW(),INTERVAL 6 YEAR)
 THEN '14'
 WHEN hiredate < DATE_SUB(NOW(),INTERVAL 5 YEAR)
 THEN '11'
 ELSE '0'    END AS Non_Management_Accrual

你可以用DATEDIFF的方法计算两天之间的天数,然后除以365得到years。根据这些,你可以写出case语句,例如:

SELECT id, CASE WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 1
 THEN '0'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 6
 THEN '11'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 11
 THEN '14'
 ELSE '18'    
 END AS Non_Management_Accrual
 FROM emp;

这里是 SQL Fiddle.

Darshan,我最终在 MySQL 端创建了视图,然后将视图添加到上面代码的 FROM 语句中。这给了我正确的输出。谢谢

<!--- Create the Manager Monthly Accruals (Mgt) dataset --->
  <cfquery name="rsLeaveTimeManagerAccruals" datasource="care">
SELECT    username, status, active, email, hiredate, tblUsers.picture AS eP
, TIMESTAMPDIFF(YEAR, hiredate, NOW()) AS year_passed
, TIMESTAMPDIFF(MONTH, hiredate, NOW()) MOD 12 AS month_passed
, TIMESTAMPDIFF(DAY, hiredate, NOW()) MOD 365 AS day_passed
, CONCAT(TIMESTAMPDIFF(YEAR, hiredate, NOW())," years, ",TIMESTAMPDIFF(MONTH, hiredate, NOW()) MOD 12," months, ",TIMESTAMPDIFF(DAY, hiredate, NOW()) MOD 365," days") AS EmployLengthActive
, TIMESTAMPDIFF(YEAR, hiredate, NOW()) AS monthly_accrual_time

, CASE WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) < 1
 THEN '0'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) <= 5
 THEN '14'
 WHEN FLOOR(DATEDIFF(NOW(), hiredate) / 365) >= 6
 THEN '18'
 END AS Management_Accrual


FROM      v_reports_to_mgt_list LEFT OUTER JOIN tblusers ON tblusers.ID = v_reports_to_mgt_list.id
WHERE     clr_accrual = '1' AND hiredate  IS NOT NULL
ORDER BY  hiredate
</cfquery>