Navigation

Feed your aggregator (RSS 2.0)   Send mail to the author(s)

Recent Entries
Archives
<July 2010>
SunMonTueWedThuFriSat
27282930123
45678910
11121314151617
18192021222324
25262728293031
1234567


Categories
Blogroll
Login

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.


Copyright 2010 Manish Kumar Singh
 Sunday, June 07, 2009
Fun with SQL Query

Find Nth Max or Min Record

This query gets the Nth highest salary from the emp table. You can replace the Max function with Min to obtain Nth lowest salary.

SELECT Eno, Ename, Desig, Sal, Mgr, DNO
FROM dbo.Emp AS
E1
WHERE (N - 1 =
 
         (SELECT COUNT(DISTINCT Sal) AS
DistinctSal 
            FROM dbo.Emp AS E2 WHERE (Sal > E1.Sal)))

Row Number

This query generates the row number for the records fetched.

SELECT (SELECT COUNT(*) AS Counter 
               FROM dbo.Emp AS
e2 
               WHERE (e2.Eno <= e.Eno)) AS RowNumber,
 
            
Ename, Desig,
Sal 
            FROM dbo.Emp AS

            
ORDER BY
RowNumber

Running Total

This query computes the running total on salary for the records in Emp table.

SELECT a.Ename, SUM(b.Sal) AS RunningTotal
FROM dbo.Emp AS
a
INNER JOIN dbo.Emp AS b ON a.Ename >= b.
Ename
GROUP BY a.Ename

Find Duplicates

This query finds the duplicate records in Emp table.

SELECT Ename, Desig, Sal, COUNT(*) AS Duplicate
FROM dbo.
Emp
GROUP BY Ename, Desig,
Sal
HAVING (COUNT(*) > 1
)
ORDER BY Duplicate DESC, Ename

Let SQL Generate SQL

This query emits SQL queries as records fetched.

Select 'Select DName from Dept where Dno=' + CAST(DNO as varchar) from Emp


SQL
Sunday, June 07, 2009 6:07:50 AM (GMT Standard Time, UTC+00:00)  #  Comments [0] Trackback