Sql 使用count distinct查找字段中具有2个或更多不同值的记录
我有一个简单的问题:如何在SQL(确切地说是Oracle)中使用Count(Distinct)只返回给定字段中有两个或多个不同值的行 通过示例更容易理解这一点:Sql 使用count distinct查找字段中具有2个或更多不同值的记录,sql,oracle,count,aggregate-functions,Sql,Oracle,Count,Aggregate Functions,我有一个简单的问题:如何在SQL(确切地说是Oracle)中使用Count(Distinct)只返回给定字段中有两个或多个不同值的行 通过示例更容易理解这一点: ACCOUNT SALESMAN 123 Abc 123 Abc 246 Abc 246 Def 246 Def 369 Hij 456 Abc 456 Def 在本例中,只有两个不同的销售代表
ACCOUNT SALESMAN
123 Abc
123 Abc
246 Abc
246 Def
246 Def
369 Hij
456 Abc
456 Def
在本例中,只有两个不同的销售代表的账户是246和456,因此,我希望查询结果只显示两个或更多销售人员共享的账户:
ACCOUNT SALESMAN
246 Abc
246 Def
456 Abc
456 Def
谢谢。使用
拥有:
select distinct account,salesman
from MyTable where account in
(
select account
from MyTable
group by account
having count(distinct salesman) >= 2
)
order by 1,2
这是一个。,因为另一个答案表明,您需要使用have
,但不能在指定的庄园中使用。使用have
SELECT DISTINCT T.Account, T.SalesMan
FROM T
INNER JOIN
( SELECT Account
FROM T
GROUP BY Account
HAVING COUNT(DISTINCT SalesMan) > 1
) Dupes
ON Dupes.Account = T.Account
您可以通过以下方式使用简单的分组:
select account
from t
group by account
having count(distinct salesperson) > 1
这将返回帐户,因此结果与您指定的不同。获取销售人员的一种方法是使用Listag:
select account, listagg(salesperson, ',')
from t
group by account
having count(distinct salesperson) > 1
否则,Gareth的答案将按照您在问题中指定的方式返回结果。这是不对的!如果按销售人员分组,则计数(不同的销售人员)
将始终为1,因此此查询将永远不会返回任何结果。可能重复的