gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 01:36:56 25 4
gpt4 key购买 nike

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

这是一个架构:

  • col1 - INT
  • col2 - INT
  • col3 - INT
  • 时间戳 - 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 |
+------+------+------+

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

最佳答案

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

关于mysql - 查找 MySQL 表中每一列的最后一个非 NULL 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39501652/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com