Select unique records from a table

Find unique rows from the table based on a single column and multiple columns.


Table: Employee                            
+----+-------+--------+--------------+     
| Id | Name  | Salary | DepartmentId |     
+----+-------+--------+--------------+     
1  | Ram   | 85000  | 1            |    
2  | Henry | 80000  | 2            |    
3  | Sam   | 60000  | 2            |    
4  | Shyam | 60000  | 1            |
5  | Ram   | 90000  | 2            |
6  | Shyam | 90000  | 1            |
7  | Leela | 80000  | 1            |
8  | Geeta | 70000  | 1            |
+----+-------+--------+--------------+

Unique Records based on Employee Name

+----+-------+--------+--------------+     
| Id | Name  | Salary | DepartmentId |     
+----+-------+--------+--------------+     
1  | Ram   | 85000  | 1            |    
2  | Henry | 80000  | 2            |    
3  | Sam   | 60000  | 2            |    
4  | Shyam | 60000  | 1            |
7  | Leela | 80000  | 1            |
8  | Geeta | 70000  | 1            |
+----+-------+--------+--------------+

Unique Records based on Employee
Name and DepartmentId

+----+-------+--------+--------------+     
| Id | Name  | Salary | DepartmentId |     
+----+-------+--------+--------------+     
1  | Ram   | 85000  | 1            |    
2  | Henry | 80000  | 2            |    
3  | Sam   | 60000  | 2            |    
4  | Shyam | 60000  | 1            |
5  | Ram   | 90000  | 2            |
7  | Leela | 80000  | 1            |
8  | Geeta | 70000  | 1            |
+----+-------+--------+--------------+


Approach:

Mysql

// Unique based on name only
Select Id, Name, Salary, DepartmentId 
from Employee GROUP BY Name;


// Unique based on name and department
Select Id, Name, Salary, DepartmentId 
from Employee GROUP BY Name
DepartmentId;


Oracle


// Unique based on name only
Select Id, Name, Salary, DepartmentId 
from Employee GROUP BY Name;


// Unique based on name and department
Select Id, Name, Salary, DepartmentId 
from Employee 
GROUP BY Name, DepartmentId;


No comments:

Post a Comment