如何在SQL中明智地分组?

时间:2015-12-03 12:18:28

标签: java mysql sql

我跟随表My_Table,其结构如下,

Name   | Address
----------------
Test1  | abc
Test1  | abc
Test2  | abc
Test1  | xyz
Test2  | abc
Test3  | abc
Test4  | tyu

我需要输出如下,

Name   | Address
----------------
Test2  | abc
Test3  | abc

让我解释一下输出。输出是按块分组数据,如果第二列包含基于Name的所有分组数据相同且等于abc,则选择该行。

详细说明: Test1有2个不同的值,其中一个不等于abc,因此它不在输出中。 Test2和Test3有一个不同的值,它等于abc,因此在输出中。 Test4有一个不同但它不等于abc,因此不在输出中。

我尝试过的,

all = select distinct(Name) from My_Table
invalid = select distinct(Name) from My_Table where Address != 'abc'

现在,所需的输出为all - invalid(减去结果集)。我用2个查询实现了这一点。这可以在一个查询中实现吗?如果是,怎么样?

注意:我使用JAVA查询MYSQL DB,因此我可以减去结果集。我的表格规模很大,因此我希望优化查询次数

1 个答案:

答案 0 :(得分:2)

select name, max(address)
from tablename
group by name
having max(address) = min(address)
   and max(address) = 'abc'
相关问题