How to find least non-null column in one particular row in SQL?

后端 未结 8 983
别跟我提以往
别跟我提以往 2020-12-29 07:36

I am trying to find the lowest number in two columns of a row in the same table, with the caveat that one of the columns may be null in a particular row. If one of the colum

8条回答
  •  -上瘾入骨i
    2020-12-29 08:15

    I've created a function which handles any number of dates, by concatenating them with a separator (CONCAT_WS) as first parameter to the function.

    CONCAT_WS besides dynamic number of parameters, will remove all NULL dates ;)

    The function accepts two parameters:

    • delimiter separated string of dates as TEXT
    • delimiter as TEXT (same as used on CONCAT_WS !!) - you can remove it if you use only preferred separator on CONCAT_WS.
    CREATE FUNCTION `min_date`(`dates` TEXT, `delim` VARCHAR(10)) RETURNS DATE NO SQL DETERMINISTIC
    BEGIN
    
    DECLARE `result` DATE DEFAULT NULL;
    
    DECLARE `count` TINYINT DEFAULT 0;
    DECLARE `temp` DATE DEFAULT NULL;
    
    IF `delim` IS NULL THEN SET `delim` = ','; END IF;
    
    IF `dates` IS NOT NULL AND CHAR_LENGTH(`dates`) > 0 THEN 
      SET `count` = LENGTH(`dates`) - LENGTH(REPLACE(`dates`, `delim`, SPACE(CHAR_LENGTH(`delim`) - 1)));
    
      WHILE `count` >= 0 DO
        SET `temp` = SUBSTRING_INDEX(SUBSTRING_INDEX(`dates`, `delim`, `count` + 1), `delim`, -1);
    
        IF `result` IS NULL OR `result` > `temp` THEN SET `result` = `temp`; END IF;
    
        SET `count` = `count` - 1;
      END WHILE;
    END IF;
    
    RETURN `result`;
    
    END
    

    Then, you can use in any combination of date fields or as static strings (as long as are valid dates or NULL):

    SELECT min_date(CONCAT_WS(',', `date_column_1`, NULL, '2019-03-04', `date_column_2`), ',') AS `min_date`
    

提交回复
热议问题