LeetCode——Duplicate Emails(使用group by以及having解决分组统计结果)

Write a SQL query to find all duplicate emails in a table named Person.

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+
For example, your query should return the following for the above table:

+---------+
| Email   |
+---------+
| a@b.com |
+---------+
Note: All emails are in lowercase.

题意:查找表中重复的Email.
此题是很典型的对分组结果进行统计筛选例题,因此可以利用group by进行分组,然后使用having统计.

# Write your MySQL query statement below
SELECT Email FROM Person GROUP BY Email HAVING COUNT(Email) > 1;

此处,对wheregroup by进行比较(引用自:https://leetcode-cn.com/problems/duplicate-emails/solution/cha-zhao-zhong-fu-de-dian-zi-you-xiang-by-he-qing-/):

  • where后不能跟聚合函数,因为where执行顺序大于聚合函数。
  • where子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,条件中不能包含聚组函数,使用where条件显示特定的行。
  • having子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚组函数,使用having条件显示特定的组,也可以使用多个分组标准进行分组。
posted @ 2019-10-09 17:17  从此寂静无声  阅读(246)  评论(0编辑  收藏  举报