gpt4 book ai didi

mysql - 从同一个表 MySQL 中选择最大日期或空日期

转载 作者:行者123 更新时间:2023-11-29 23:16:50 25 4
gpt4 key购买 nike

我会选择最大日期或空,但公司代码显示两次。

原表为

Employee code      Company Code     resignation date
001 A 1/2/2013
001 B 30/12/2014
002 B 10/10/2000
003 A 1/12/2014
003 c NULL

应该显示

EMPLOYEE_CODE      COMPANY_CODE     RESIGNATION_DATE
001 B 30/12/2014
002 B 10/10/2000
003 C NULL

但我只想为每个 EMPLOYEE_CODE 显示一条记录

EMPLOYEE_CODE      COMPANY_CODE     RESIGNATION_DATE
001 A 1/2/2013
001 B 30/12/2014
002 B 10/10/2000
003 C

这是我的查询

SELECT EMPLOYEE_CODE , COMPANY_CODE, RESIGNATION_DATE
FROM MT_EMPLOYEE_CONTRACT WHERE RESIGNATION_DATE IS NULL
UNION
SELECT EMPLOYEE_CODE , COMPANY_CODE, MAX(RESIGNATION_DATE) AS RESIGNATION_DATE
FROM MT_EMPLOYEE_CONTRACT WHERE WHERE EMPLOYEE_CODE NOT IN
(SELECT EMPLOYEE_CODE FROM MT_EMPLOYEE_CONTRACT WHERE RESIGNATION_DATE IS NULL)
GROUP BY EMPLOYEE_CODE;

谁能找出问题所在吗?谢谢

最佳答案

已更新

请尝试更正后的版本:

SELECT 
MT_EMPLOYEE_CONTRACT.EMPLOYEE_CODE ,
MT_EMPLOYEE_CONTRACT.COMPANY_CODE,
MT_EMPLOYEE_CONTRACT.RESIGNATION_DATE
FROM
MT_EMPLOYEE_CONTRACT
INNER JOIN
(
SELECT
A.EMPLOYEE_CODE ,
MAX(A.RESIGNATION_DATE) AS MAX_RESIGNATION_DATE
FROM
MT_EMPLOYEE_CONTRACT AS A
GROUP BY
A.EMPLOYEE_CODE
) AS B
ON MT_EMPLOYEE_CONTRACT.EMPLOYEE_CODE = B.EMPLOYEE_CODE
AND MT_EMPLOYEE_CONTRACT.RESIGNATION_DATE = B.MAX_RESIGNATION_DATE;
WHERE
NOT ISNULL(MT_EMPLOYEE_CONTRACT.RESIGNATION_DATE)

UNION

SELECT
MT_EMPLOYEE_CONTRACT.EMPLOYEE_CODE ,
MT_EMPLOYEE_CONTRACT.COMPANY_CODE,
MT_EMPLOYEE_CONTRACT.RESIGNATION_DATE
FROM
MT_EMPLOYEE_CONTRACT
WHERE
ISNULL(MT_EMPLOYEE_CONTRACT.RESIGNATION_DATE)

关于mysql - 从同一个表 MySQL 中选择最大日期或空日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27715385/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com