SQL使用GROUP BY,包含COUNT个选择包含空字段的行

时间:2018-08-06 19:01:05

标签: sql sql-server group-by having

我想做的事情与Select first row in each GROUP BY group?

非常相似

除了选择ORDER BY number DESC之后的第一行外,我想选择一行在数据库中多次显示(过去已更改名称)并且在Change_Name_to下为空字段。

例如,我有一个表,该表显示人员的姓名更改历史记录和当前姓名。

+--------+--------------+----------------+
| 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

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

3 个答案:

答案 0 :(得分:3)

我认为您可以使用自己想做的事

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
             );

答案 1 :(得分:2)

基于该示例数据,您只需

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)

答案 2 :(得分:0)

检查下一个:

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;