使用多列列中的值获取最后一列

时间:2017-09-29 17:28:51

标签: sql database


我有一个具有下一个数据示例的特定表格

+----+-----------+-----------+-------------+---------+------------+
| 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 |
+----+-----------+-----------+-------------+---------+------------+

我想得到下一个结果
结果示例:

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

我该怎么办?可能吗?如果可以的话,我想听听主要的想法和例子。

2 个答案:

答案 0 :(得分:1)

THEN

答案 1 :(得分:0)

我建议将您的表格规范化为这种结构((id, level), name, value),这样可以更容易查询,例如:

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

如果您真的想坚持自己的结构,并且知道您将在表格中列出的等级数量,那么这也是一个选项:

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;