简体   繁体   中英

Getting last column with values from multiples columns


I have a specific table with the next data example

+----+-----------+-----------+-------------+---------+------------+
| id |   name    |  level1   |   level2    | level3  |   level4   |
+----+-----------+-----------+-------------+---------+------------+
|  1 | juan      | operation | 0           | 0       | 0          |
|  2 | pedro     | operation | maintance   | user    | 0          |
|  3 | guillermo | operation | client      | 0       | 0          |
|  4 | mario     | operation | coordinator | factory | productive |
+----+-----------+-----------+-------------+---------+------------+

I would like to get the next result
Result example:

+----+-----------+------------------------+
| id |   name    | last level with values |
+----+-----------+------------------------+
|  1 | juan      | operation              |
|  2 | pedro     | user                   |
|  3 | guillermo | client                 |
|  4 | mario     | productive             |
+----+-----------+------------------------+

How can I do it? is it possible? I would like to hear the main idea and example if you can.

SELECT 
 id,
 name,
 COALESCE(
  NULLIF(level4,'0'),
  NULLIF(level3,'0'),
  NULLIF(level2,'0'),
  level1
 ) AS "last level with values"
FROM ... 

I'd suggest to normalize your table into such kind of a structure ((id, level), name, value) and this is going to be far easier to query, for instance:

SELECT *
FROM table AS t1
WHERE t1.level = (  SELECT MAX(t2.level)
                    FROM table AS t2
                    WHERE t2.id = t1.id);

If you really want to stick to your structure and know amount of levels you're going to have in your table as columns, this could be an option too:

SELECT id
  , name
  , CASE
    WHEN level4 <> 0 THEN level4
    WHEN level3 <> 0 THEN level3
    WHEN level2 <> 0 THEN level2
    ELSE level1
  END AS lastLevelWithValues
FROM table;

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