MySQL Case语句“调整”

时间:2018-07-24 15:09:18

标签: mysql

我有以下工作查询,以小时为单位计算员工的应计时间,但是我需要将11和14更改为(14&18)IF manager = 1

这是我当前的代码:

CASE 
WHEN TIMESTAMPDIFF(DAY,hiredate,NOW()) < 1
THEN '0'
WHEN TIMESTAMPDIFF(DAY,hiredate,NOW()) >= 1 AND TIMESTAMPDIFF(MONTH, 
hiredate, NOW()) <= 60
THEN '11'
WHEN TIMESTAMPDIFF(MONTH, hiredate, NOW()) >= 61 AND TIMESTAMPDIFF(MONTH, 
hiredate, NOW()) <= 120
THEN '14'
ELSE '18'    
END AS monthly_Accrual_Level

如何添加额外的变量“ manager = 1”以覆盖以下情况:

  • 当结果= 11,但员工是经理时,将时间设为14
  • 当结果= 14,但员工是经理时,将他的时间设为18

2 个答案:

答案 0 :(得分:2)

您可以使用“小写”:

CASE
...
WHEN TIMESTAMPDIFF(DAY,hiredate,NOW()) >= 1 AND TIMESTAMPDIFF(MONTH, 
hiredate, NOW()) <= 60
THEN CASE WHEN manager = 1 THEN '14' ELSE '11' END
... —- similar for other manager value
END AS monthly_Accrual_Level

或将条件的每一边添加到WHEN:

CASE
...
WHEN TIMESTAMPDIFF(DAY,hiredate,NOW()) >= 1 AND TIMESTAMPDIFF(MONTH, 
hiredate, NOW()) <= 60
AND manager = 1 THEN '14'
WHEN TIMESTAMPDIFF(DAY,hiredate,NOW()) >= 1 AND TIMESTAMPDIFF(MONTH, 
hiredate, NOW()) <= 60
AND manager != 1 THEN '11'
... —- similar for other manager value
END AS monthly_Accrual_Level

我更喜欢“小写”,因为它可以更准确地抓住您用英语表达的意图,但是请选择您更容易阅读的那个。

答案 1 :(得分:0)

感谢波西米亚人的出色帮助!

这是我最终得到的解决方案:

CASE
    WHEN TIMESTAMPDIFF( DAY, hiredate, NOW( ) ) < 1 THEN '0' WHEN TIMESTAMPDIFF( DAY, hiredate, NOW( ) ) >= 1 

        AND TIMESTAMPDIFF( MONTH, hiredate, NOW( ) ) <= 60 AND manager != 1 THEN '11' WHEN TIMESTAMPDIFF( DAY, hiredate, NOW( ) ) >= 1 
        AND TIMESTAMPDIFF( MONTH, hiredate, NOW( ) ) <= 60 AND manager = 1 THEN '14' WHEN TIMESTAMPDIFF( DAY, hiredate, NOW( ) ) >= 1 

        AND TIMESTAMPDIFF( MONTH, hiredate, NOW( ) ) <= 120 AND manager != 1 THEN '14' WHEN TIMESTAMPDIFF( DAY, hiredate, NOW( ) ) >= 1 
        AND TIMESTAMPDIFF( MONTH, hiredate, NOW( ) ) <= 120 AND manager = 1 THEN '18' 
    ELSE '18' 
END AS monthly_Accrual_Level