Navigation

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

Recent Entries
Archives
<February 2012>
SunMonTueWedThuFriSat
2930311234
567891011
12131415161718
19202122232425
26272829123
45678910


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 2012 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 [1] Trackback
Monday, November 14, 2011 10:48:32 PM (GMT Standard Time, UTC+00:00)
I must say that this script will be useful in some situations
Name
E-mail
Home page

Comment (Some html is allowed: a@href@title, strike) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Enter the code shown (prevents robots):

Live Comment Preview