查找MySQL表中每列的最后一个非NULL值?

时间:2016-09-15 00:45:37

标签: mysql sql null

我有一个包含col1col2col3列的表格。在每一行中,这些值中只有一个不为空。我想找到col1col2col3的最新值(显然来自三个不同的行),其中不是NULL

这是一个架构:

  • col1 - INT
  • col2 - INT
  • col3 - INT
  • timestamp - DATETIME

假设我有这些数据:

+------+------+------+------------------+
| col1 | col2 | col3 |    timestamp     |
+------+------+------+------------------+
| 1    | NULL | NULL | 15/09/2016 10:55 |
| NULL | 2    | NULL | 15/09/2016 10:56 |
| NULL | NULL | 3    | 15/09/2016 10:57 |
| 4    | NULL | NULL | 15/09/2016 10:58 |
+------+------+------+------------------+

我想要以下结果:

+------+------+------+
| col1 | col2 | col3 |
+------+------+------+
|    4 |    2 |    3 |
+------+------+------+

如何编写查询来执行此操作?

3 个答案:

答案 0 :(得分:3)

select
  (select col1 from tbl where col1 is not null order by timestamp desc limit 1) as col1,
  (select col2 from tbl where col2 is not null order by timestamp desc limit 1) as col2,
  (select col3 from tbl where col3 is not null order by timestamp desc limit 1) as col3

答案 1 :(得分:1)

假设您有一个列,例如指定排序的timestamp,那么您可以使用以下内容获取每个列的最后一个ID:

select max(case when col1 is not null then timestamp end) as ts1,
       max(case when col2 is not null then timestamp end) as ts2,
       max(case when col3 is not null then timestamp end) as ts3
from t;

然后,您可以使用join

获取所需的行
select t.*
from t join
     (select max(case when col1 is not null then timestamp end) as ts1,
             max(case when col2 is not null then timestamp end) as ts2,
             max(case when col3 is not null then timestamp end) as ts3
      from t
     ) tt
     on t.timestamp in (ts1, ts2, ts3)

答案 2 :(得分:0)

使用以下内容:

 col1    col2    col3  timestamp
  1       2        8   2016-09-02 10:00:00
  0       4        10  2016-09-04 12:00:00   

更新了帖子:

 col1    col2    col3 
   1       4      10

表格结构:

{{1}}

返回:

{{1}}