I have a simple question: How can I use Count(Distinct) in SQL (Oracle to be exact) to return only the rows where there are two or more different values in a given field.
This is easier understood by example:
ACCOUNT SALESMAN
123 Abc
123 Abc
246 Abc
246 Def
246 Def
369 Hij
456 Abc
456 Def
In this example, the only Accounts with 2 different sales reps would be 246 and 456, and thus, I'd want the query's result to just show the the accounts shared by 2 or more salesmen:
ACCOUNT SALESMAN
246 Abc
246 Def
456 Abc
456 Def
Thanks.
You can use the combination of the SUM and COUNTIF functions to count unique values in Excel. The syntax for this combined formula is = SUM(IF(1/COUNTIF(data, data)=1,1,0)). Here the COUNTIF formula counts the number of times each value in the range appears.
The correct syntax for using COUNT(DISTINCT) is: SELECT COUNT(DISTINCT Column1) FROM Table; The distinct count will be based off the column in parenthesis. The result set should only be one row, an integer/number of the column you're counting distinct values of.
Answer. Yes, the DISTINCT clause can be applied to any valid SELECT query. It is important to note that DISTINCT will filter out all rows that are not unique in terms of all selected columns.
Using DISTINCT in aggregationsYou can use DISTINCT when performing an aggregation. You'll probably use it most commonly with the COUNT function. In this case, you should run the query below that counts the unique values in the month column.
use having
:
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
Here is a demonstration.
As the other answer has indicated you need to use HAVING
, but not in the manor indicated. You need to join back to the original table after using HAVING
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
SQL Fiddle
You can do this with a simple GROUP BY/HAVING query:
select account
from t
group by account
having count(distinct salesperson) > 1
This returns the accounts, so the result is different from what you specify. One way to get the sales people is to use listagg:
select account, listagg(salesperson, ',')
from t
group by account
having count(distinct salesperson) > 1
Otherwise, Gareth's answer returns the results the way you specified in the question.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With