-2

I ve a table named as tbl_Emp:

enter image description here

Now I want to select Unique Emp_Name with EmpID and EmpSalary as follows.I just want to know that what will be the Common table expression in SQL to do this.

enter image description here

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326

3 Answers3

2

This is a simple query using CTE

WITH CTE AS(   
SELECT ROW_NUMBER() OVER(PARTITION BY EmpName ORDER BY EmpID) AS ROWNO,    
                    EmpID,EmpName, EmpSalary FROM tbl_emp
) 
SELECT EmpID, EmpName, EmpSalary  FROM CTE WHERE ROWNO = 1 order by EmpID

If you want Remove the duplicate data use the script as bellow

WITH CTE AS(   
    SELECT ROW_NUMBER() OVER(PARTITION BY EmpName ORDER BY EmpID) AS ROWNO,    
                        EmpID, EmpName, EmpSalary FROM tbl_emp
    ) 
    DELETE FROM CTE WHERE ROWNO > 1

I think the query can help you

user2460074
  • 1,252
  • 3
  • 11
  • 28
0

I don't think there's a need for a CTE on this. I would JOIN the table with itself. Something like:

SELECT t.* FROM tbl_Emp t
INNER JOIN
(
  select MIN(EmpID) FirstEmp from tbl_Emp group by EmpName
) t2
ON t2.FirstEmp=t.EmpID;

Basically, I'm joining in a second table that has the lowest EmpID field of each distinct EmpName, then selecting all rows that match one of those EmpID fields.

SQL Fiddle

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
  • Great it works. Now If I want to remove duplicate records from tbl_Emp what will be the simplest SQL query? – Md. Saidujjaman Sajib Jan 05 '16 at 04:44
  • I think you should post this as a new question. But I'd do a bit of research first, since there are _many_ duplicates. If my answer meets your criteria, please hit the _Accept_ button. Thanks! – Mike Christensen Jan 05 '16 at 05:54
0

It looks like you are looking for DISTINCT.

something like:

SELECT DISTINCT Emp_Name, EmpID, EmpSalary
FROM tbl_emp;
Rabbi Shuki Gur
  • 1,656
  • 19
  • 36