我有一个包含col1
,col2
,col3
列的表格。在每一行中,这些值中只有一个不为空。我想找到col1
,col2
和col3
的最新值(显然来自三个不同的行),其中不是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 |
+------+------+------+
如何编写查询来执行此操作?
答案 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}}