首页 > 解决方案 > 如何在mysql中的相应列的单行中获取多个行值

问题描述

我有一张这样的桌子

table   | last_access  | last_read   | read_by  |  last_write  |  write_by |   last_str_change |   str_change_by

tab1    | 01-02-21     | 01-02-21    | user1    | null         | null      |  null            |  null
tab1    | 02-02-21     | null        | null     | 02-02-21     | user2     |  null            |  null
tab1    | 03-02-21     | null        | null     | null         | null      | 03-02-21         |  user3

我需要这种格式

table    last_access   last_read   read_by   last_write   write_by    last_str_change    str_change_by
tab1     03-02-21      01-02-21    user1      02-02-21    user2       03-02-21           user3

last_access 列应该具有来自 last_read、last_write、last_str_change 列的最大或最新日期,并且列 last_read、last_write、last_str_change 数据应该在一行中。

提前致谢。

标签: mysqlsql

解决方案


使用聚合:

select table, max(last_access), max(last_read), max(last_write), max(last_str_change)
from t
group by table;

推荐阅读