How to select distinct values from multiple columns?
Let’s say we have a table employee as the following picture:
and we want to get the results are only DISTINCT job and mgr columns. So let’s query as the following:
SELECT DISTINCT
job,mgr
FROM emp
WHERE mgr is not null;
when query processing the results are be able to like this:
but wait as we know that when we use DISTINCT keyword in SQL columns which are selected of results must be unique, however our results are still repeated again.
The reason this to happen that DISTINCT are going to select all columns not only once. That’s why I wrote a article about this. A lots of people understand that DISTINCT only retrive unique values when he or she still did not encounter that problem.
So without any further ado let’s get started solving this problem. In order to solve this problem we use GROUP BY keyword instead of DISTINCT:
SELECT
job,max(mgr) mgr
FROM emp
where mgr is not null
GROUP BY job;
Then results are be able to like this: