Complex SQL Coding questions and Answers
Complex SQL Coding questions and Answers
ANS::
select * from EmployeeSalary;
To See how many duplicate records are available
Select employeeID,JobTitle,Salary, count(*) as cnt
from EmployeeSalary group by employeeID having cnt>1;
Create a table
Create Table EmployeeSalary
(SN int PRIMARY KEY,
EmployeeID int,
JobTitle varchar(50),
Salary int)
Insert values into table
Insert Into EmployeeSalary
VALUES
(1,1001, 'Salesman', 45000),
(2,1002, 'Receptionist', 36000),
(3,1002, 'Receptionist', 36000),
(4,1002, 'Receptionist', 36000),
(5,1003, 'Salesman', 63000),
(6,1004, 'Accountant', 47000),
(7,1005, 'HR', 50000),
(8,1006, 'Regional Manager', 65000),
(9,1006, 'Regional Manager', 65000),
(10,1007, 'Supplier Relations', 41000),
(11,1008, 'Salesman', 48000),
(12,1009, 'Accountant', 42000),
(13,1009, 'Accountant', 42000)
With CTE
with cte as(
select SN, EmployeeID,JobTitle, Salary,row_number()
over (partition by EmployeeID,JobTitle, Salary order by EmployeeID,JobTitle,
Salary)row_num
From EmployeeSalary1)
select * from CTE where row_num>1
With RANK()
Select E.EmployeeID,
E.JobTitle,
E.Salary,
T.srank from EmployeeSalary E
inner join
(Select *,
Rank() over (Partition By EmployeeID
order by SN,EmployeeID)srank
from EmployeeSalary) T on E.EmployeeID=T.EmployeeID;
worked
with Temp as(
select SN, EmployeeID,JobTitle, Salary,
rank() over (partition by EmployeeID,JobTitle, Salary order by EmployeeID,SN)s_rank
From EmployeeSalary)
select * from temp where s_rank>=1
ANS:: Select Max(Amount) from Orders where Amount < ( Select Max(Amount) From
orders order by Amount desc);
Nth highest Salary:
Select Min(Amount) from (Select Distinct(Amount) From orders order by Amount desc limit
3 );
Select Min(Price) From (Select Distinct Price
From Products Order by Price Desc
Limit 3);
Using Self Join::
Select Distinct(Amount) from orders A where 3= (Select count(Distinct(Amount)) From
orders B Where A.Order_ID<=B.Order_ID )order by A.Amount Desc;
3. How to create the Orders_1 table, which is exact replica of Orders table?
Ans:: Create table Orders_1 as Select * From Orders;
13. How to get distinct records from the table without using distinct keyword?
ANS:
select * from EmployeeSalary a where rowid = (select max(rowid) from EmployeeSalary
b where a.EmployeeID=b.EmployeeID);
14. Select all records from Employee table whose name is not ‘John’
Ans:
Select * From Customers Where First_Name NOT IN ('John');