Sunday, 27 November 2016

SQL Querys

2nd Highest salary in SQL

Method 1:   Select salary from employee where salary<(select max(salary) fro employee)---2nd          Highest salary

Method 2 : Select salary from (select distinct top 2 salary from employee order by salary desc)    Result order by salary--2nd highest salary

Method 3 :
Using CTE

WITH RESULT AS
(
Select salary,DENSE_RANK() over (order by salary DESC) as Denserank from Employee)
select top1 salary
from RESULT
where Result.DENSERANK=2  //--Getting second Highest sal if we want 3 Highest sal then put 3
========================================================================

How to update Male to Female and Female to Male in sql server

UPDATE table SET gender = 
CASE gender WHEN 'male' THEN 'female' 
                   WHEN 'female' THEN 'male' 
 ELSE gender END 

=======================================================

Write SQL Query to find duplicate rows in a database? and then write SQL query to delete them?

You can use the following query to select distinct records:
SELECT * FROM emp a WHERE rowid = (SELECT MAX(rowid) FROM EMP b WHERE a.empno=b.empno)

to Delete:

DELETE FROM emp a WHERE rowid != (SELECT MAX(rowid) FROM emp b WHERE a.empno=b.empno);

No comments:

Post a Comment