MySQL选择最大日期或空日期

时间:2014-04-22 08:50:27

标签: mysql sql

我会选择最大日期或null但它会显示错误消息。

  

错误:SQLCODE = -104,SQLSTATE = 42601,SQLERRMC = IS;,MAXE时的情况(日期; CONCAT,DRIVER = 3.64.114

原始表是

Employee code           resignation date
001                     1/2/2013
001                     1/5/2014
001                     null
002                     10/10/2000

应该显示

EMPLOYEE_CODE           RESIGNATION_DATE
001                     null
002                     10/10/2000

这是我的查询

SELECT EMPLOYEE_CODE, 
       CASE 
           WHEN MAX(RESIGNATION_DATE IS NULL)= 0 
           THEN MAX(RESIGNATION_DATE) 
       END AS DATE
FROM MT_EMPLOYEE_CONTRACT
GROUP BY EMPLOYEE_CODE;

任何人都可以找出问题所在吗? 谢谢

2 个答案:

答案 0 :(得分:2)

  

任何人都可以找出问题所在吗?

在这种情况下:

MAX(RESIGNATION_DATE IS NULL)= 0

您将MAX(NULL)=0RESIGNATION_DATE IS NULL

进行比较

您的查询应该是:

select emp_code, res_date /* first select null emp_code*/
From Table_name
where res_date IS NULL group by emp_code
UNION 
select emp_code, MAX(res_date ) /* select max from non - null emp_code*/
From Table_name
where emp_code NOT IN 
     (select emp_code From Table_name 
      where res_date IS NULL) 
group by emp_code

修改

select DISTINCT emp_code, res_date /* first select null emp_code*/
From Table_name
where res_date IS NULL 
UNION 
select emp_code, MAX(res_date ) /* select max from non - null emp_code*/
From Table_name
where emp_code NOT IN 
     (select emp_code From Table_name 
      where res_date IS NULL) 
group by emp_code 

答案 1 :(得分:0)

尝试使用NULLIFIFNULL函数的组合。

SELECT EMPLOYEE_CODE, NULLIF(MAX(IFNULL(RESIGNATION_DATE,0)),0)
FROM MT_EMPLOYEE_CONTRACT
GROUP BY EMPLOYEE_CODE;