Programing

MySQL : 여러 열의 MAX 또는 GREATEST를 가져 오지만 NULL 필드

crosscheck 2021. 1. 10. 19:13

MySQL : 여러 열의 MAX 또는 GREATEST를 가져 오지만 NULL 필드


각 레코드 (MySQL)의 세 가지 다른 필드에서 최대 날짜를 선택하려고합니다. 따라서 각 행에는 date1, date2 및 date3이 있습니다. date1은 항상 채워지고 date2 및 date3은 NULL이거나 비어있을 수 있습니다. GREATEST 문은 다음과 같습니다. 간단하고 간결하지만 NULL 필드에는 영향을 미치지 않으므로 제대로 작동하지 않습니다.

SELECT id, GREATEST(date1, date2, date3) as datemax FROM mytable

다음과 같은 더 복잡한 솔루션도 시도했습니다.

SELECT
    CASE
        WHEN date1 >= date2 AND date1 >= date3 THEN date1
        WHEN date2 >= date1 AND date2 >= date3 THEN date2
        WHEN date3 >= date1 AND date3 >= date2 THEN date3
        ELSE                                        date1
    END AS MostRecentDate

동일한 문제 : NULL 값은 올바른 레코드를 반환하는 데 큰 문제입니다.

제발, 해결책이 있습니까? 미리 감사드립니다 ....


사용하다 COALESCE

SELECT id, 
   GREATEST(date1, 
     COALESCE(date2, 0),
     COALESCE(date3, 0)) as datemax 
FROM mytable

업데이트 : 이전에 사용 IFNULL이 답변 은 작동하지만 Mike Chamberlain이 의견에서 지적했듯이 COALESCE실제로 선호되는 방법입니다.


date1결코 될 수 없다면 NULL, 결과는 결코 될 수 없습니다 NULL. 그럼 당신은 당신이 원하는 경우,이 사용할 수 NULL날짜 계산에 포함되지 수 (또는 변경 1000-01-019999-12-31당신이 널 (null)은 "시간의 끝"으로 간주 할 경우) :

GREATEST( date1
        , COALESCE(date2, '1000-01-01')
        , COALESCE(date3, '1000-01-01')
        ) AS datemax

COALESCE에서 사용하기 전에 날짜 열을 GREATEST.

당신이 그들을 다루는 방법은 당신이 어떻게 처리하고 싶은지에 달려 있습니다 NULL.. 높거나 낮습니까?


buuut, 모든 날짜가 null이면? 여전히 출력으로 null을 원하십니까? 그럼이게 필요해

select nullif(greatest(coalesce(<DATEA>, from_unixtime(0)), coalesce(<DATEB>, from_unixtime(0))), from_unixtime(0));

이제 둘 다 null이면 null을 얻습니다. 둘 중 하나가 null이 아니면 둘 다 null이 아니면 가장 큰 값을 얻습니다.

이것은 미친 짓입니다. 특히 여러 번 사용할 경우 다음과 같이 함수로 생성 할 수 있습니다.

delimiter //
drop function if exists cp_greatest_date//
create function cp_greatest_date ( dateA timestamp, dateB timestamp ) returns timestamp
  deterministic reads sql data
  begin

    # if both are null you get null, if one of them is not null of both of them are not null, you get the greatest
    set @output = nullif(greatest(coalesce(dateA, from_unixtime(0)), coalesce(dateB, from_unixtime(0))), from_unixtime(0));
    # santiago arizti

    return @output;
  end //
delimiter ;

그러면 이렇게 사용할 수 있습니다

select cp_greatest_date(current_timestamp, null);
-- output is 2017-05-05 20:22:45

ReferenceURL : https://stackoverflow.com/questions/9831851/mysql-get-max-or-greatest-of-several-columns-but-with-null-fields