简体   繁体   中英

Fill empty row with value of previous row mysql

There is a table with single column having few null and empty values.

colName
null
null
A
null
-
B
null

I need to fill the null or empty values with the above non empty value.

colName
null
null
A
A
A
B
B

I tried following query, but it fails.

SELECT  
(CASE WHEN colName IS NULL
THEN @prevValue
ELSE @prevValue := colName END) Value
FROM myValues t1
CROSS JOIN (SELECT @prevValue := NULL) t2


/*As the table does not contain any primary column or identity column, so one can not decide which value is the previous value. It will be random.

The value set above is small that is why below query will work without any issues.
If it is larger then go ahead and put an identity column and
replace the Row number column with Identity column in the query*/

SELECT 
CASE 
    WHEN myValues1.colName IS NULL AND myValues2.colName IS NOT NULL THEN   myValues2.colName 
    /**Selecting the previous NOT NULL value for a NULL value*/  
    WHEN myValues1.colName='' AND myValues2.colName IS NOT NULL THEN myValues2.colName  
    /**Selecting the previous NOT NULL value for an empty value*/ 
    WHEN myValues1.colName='' AND myValues2.colName IS NULL THEN (SELECT TOP 1 colName FROM (SELECT colname,
                                row_number() OVER (ORDER BY (SELECT 0)) AS rowNumber 
                                FROM myValues) myValues3 WHERE myValues3.rowNumber < myValues2.rowNumber 
                                AND myValues3.rowNumber IS NOT NULL 
                                AND myValues3.rowNumber<>'' ORDER BY myValues3.rowNumber DESC)
/**Selecting the prior NOT NULL value for an empty value*/ 
    WHEN myValues1.colName IS NULL AND myValues2.colName='' THEN (SELECT TOP 1 colName FROM (SELECT colname,
                                row_number() OVER (ORDER BY (SELECT 0)) AS rowNumber 
                                FROM myValues) myValues3 WHERE myValues3.rowNumber < myValues2.rowNumber 
                                AND myValues3.rowNumber IS NOT NULL 
                                AND myValues3.rowNumber<>'' ORDER BY myValues3.rowNumber DESC)
    /**Selecting the priorNOT NULL value for a NULL value*/  
    ELSE myValues1.colName   
    /**Selecting the same value if is not NULL or an empty value*/  
END AS colName  FROM   

(SELECT colName,  
row_number() OVER (ORDER BY (SELECT 0)) AS rowNumber   
FROM myValues) myValues1 /**Setting the row number as it is displayed*/  

LEFT OUTER JOIN   

(SELECT colName,  
row_number() OVER (ORDER BY (SELECT 0)) AS rowNumber  
FROM myValues) myValues2 /**Setting the row number as it is displayed*/  
ON myValues1.rowNumber=myValues2.rowNumber+1  /**Joining in a way to get the previous   value*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM