查找每列的最后一个非NULL值,然后将它们分组到MySQL表中?

时间:2018-02-07 04:22:20

标签: mysql sql

我有一张这样的表:

     uid |      name       | gender | age  | date
    -----+-----------------+--------+------+----------
      38 | Danny Little    | NULL   | NULL | 2018/01/01
      38 | NULL            | NULL   |   24 | 2018/01/02
      41 | NULL            | male   |   40 | 2018/01/03
      43 | OfCourseNewUser | female |   13 | 2018/01/04
      38 | NULL            | NULL   |  100 | 2018/01/05
      38 | ADanny          | male   | NULL | 2018/01/06
      38 | ADanny          | NULL   |   99 | 2018/01/07

我希望找到名称,性别和年龄的最新值(显然来自三个单独的行),其中这些不是NULL(如果有所有空值,则设置为null),然后分组uid,结果是这样的:

    uid  |      name       | gender | age
    -----+-----------------+--------+-----
     38  | ADanny          | male   | 99
     41  | NULL            | male   | 40
     43  | OfCourseNewUser | female | 13

我只需要一个查询,它可以在其他数据库中获得LAST_VALUE(列,忽略null)。但MySQL并不支持窗口函数。

我怎样才能得到这个结果?

2 个答案:

答案 0 :(得分:1)

你提到你的MySQL不支持窗口函数。然后,我想为什么不使用LEFT OUTER JOIN呢?

检查出来:

SELECT u.uid,
       u.name,
       u2.gender,
       u.age,
       u.date
FROM users u
LEFT OUTER JOIN users u2 ON u2.uid = u.uid   AND u.age IS NOT NULL
LEFT OUTER JOIN users u3 ON u3.uid = u2.uid  AND u2.gender IS NOT NULL
GROUP BY uid, name
HAVING 
    u.date = MAX(u.date)
AND u.uid IS NOT NULL
AND u.age IS NOT NULL

输出

| uid |            name | gender | age |       date |
|-----|-----------------|--------|-----|------------|
|  38 |          ADanny |   male |  99 | 2018-01-07 |
|  41 |          (null) |   male |  40 | 2018-01-03 |
|  43 | OfCourseNewUser | female |  13 | 2018-01-04 |

SQLFiddle Demo

答案 1 :(得分:-1)

试试这个。

select * from YourTable where gender!=NULL and age!=NULL order by date desc;