首页 > 解决方案 > 过滤与 SQL 中的过滤条件相对应的重复记录和出现次数

问题描述

有一个表并使用键对记录进行分组:stu_class|stu_birth|stu_major。如果有重复记录,则选择 stu_id 最小的记录。所以,我需要计算满足这个条件的记录总数。

例子:

在此处输入图像描述

这里, stu_id (100,101) 是基于键的重复记录。但我只想选择最小的 stu_id 记录。它是 stu_id , 100。类似地, stu_id (102,104) 是重复记录。但需要选择 stu_id 102。

然后选择的记录计数应该是 2。我怎样才能使用 SQL 获得这个计数?。我的意思是如何将计算出的记录总数设为 2。

标签: mysqlsql

解决方案


一种方法使用窗口函数:

select t.*
from (select t.*,
             row_number() over (partition by stu_class, stu_birth, stu_major order by stu_id) as seqnum
      from t
     ) t
where seqnum = 1;

从版本 8 开始,这在 MySQL 中可用。

一种替代方法使用相关子查询,并且可能更快,即使在版本 8 中也是如此:

select t.*
from t
where t.stu_id = (select min(t2.stu_id)
                  from t t2
                  where t2.stu_class = t.stu_class and t2.stu_birth = t.stu_birth and t2.stu_major = t.stu_major
                 );

这可以利用上的索引(stu_class, stu_birth, stu_major, stu_id)

编辑

如果您只想要总记录,请使用聚合:

select stu_class, stu_birth, stu_major, min(stu_id), count(*) as cnt
from t
group by stu_class, stu_birth, stu_major;

推荐阅读