SQL select 行包含使用 GROUP BY 的空字段,HAVING COUNT

SQL select rows containing empty field using GROUP BY, HAVING COUNT

我想要做的与每个 GROUP BY 组中的 Select 第一行非常相似?

但除了 ORDER BY number DESC 之后的第一行 select,我希望 select 一行在数据库中多次出现(过去已更改名称)并且 Change_Name_to.

例如,我有一个 table 显示人的姓名更改历史和当前姓名。

+--------+--------------+----------------+
| UserID | Current_Name | Change_Name_to |
+--------+--------------+----------------+
|     30 | Name3        |                |
|     30 | Name2        | Name3          |
|     30 | Name1        | Name2          |
|     10 | Name5        |                |
|     20 | Name7        |                |
|     20 | Name6        | Name7          |
+--------+--------------+----------------+

我想在这里做的是

+--------+--------------+----------------+
| UserID | Current_Name | Change_Name_to |
+--------+--------------+----------------+
|     30 | Name3        |                |
|     20 | Name7        |                |
+--------+--------------+----------------+

我应该怎么做?

SELECT *, COUNT(*) FROM `docs` GROUP BY id HAVING COUNT(UserID) > 1

我知道这行不通,但我想做这样的事情。

我认为您可以使用以下方法做您想做的事:

select d.*
from docs d
where d.change_name_to is null and
      exists (select 1
              from docs d2
              where d2.userid = d.userid and d2.change_name_to is not null
             );

根据该示例数据,您只需要

select * 
from docs d
where d.change_name_to is null
and UserID in (select UserID from docs group by UserID having count(UserID) > 1)

检查下一个:

SELECT
  l.UserID, l.Current_Name, l.Change_Name_to
FROM @docs l JOIN @docs r
  ON l.UserID = r.UserID AND
     l.Current_Name = r.Change_Name_to
WHERE l.Change_Name_to IS NULL AND
      r.Change_Name_to IS NOT NULL;