Re: Alternative for TOP
From: Joe Celko (jcelko212_at_earthlink.net)
Date: 08/04/04
- Next message: Aaron [SQL Server MVP]: "Re: CAST and CONVERT question - 24 hour time"
- Previous message: Partha Mandayam: "Re: AutoNumber Column and ..."
- In reply to: student: "Alternative for TOP"
- Next in thread: student: "Re: Alternative for TOP"
- Reply: student: "Re: Alternative for TOP"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 04 Aug 2004 11:08:10 -0700
SELECT TOP(n) is a proprietary feature that was easy to implement in SQL
Server because of the use of a contigous storage file system under the
covers. I have a whole chapter in SQL FOR SMARTIES with standard SQL
solutions for this problem, using top salaries as the example.
The best answer given uses a subquery to establish a subset based on a
count. The idea is take each salary and build a group of other salaries
which are less than or equal to it. The groups with three or fewer rows
is what we want to see.
This query gives a columnar answer. It can be extended to other numbers
by changing @n and playing with the two comparison operators.
SELECT DISTINCT salary
FROM Personnel AS P1
WHERE @n >= (SELECT COUNT(*) - 1 -- control parameter
FROM Personnel AS P2
WHERE P1.salary < P2.salary)
An equivalent version can also be done with a GROUP BY clause, but you
need to use a COUNT(DISTINCT x) operator to handle duplicates. Here is
that code.
SELECT P1.salary
FROM Personnel AS P1, Personnel AS P2
WHERE P1.salary <= P2.salary
GROUP BY P1.salary
HAVING COUNT(DISTINCT P2.salary) <= @n; -- control parameter
The performance of these two approaches will vary with each SQL
implementation and with the available indexing. It is probably best to
experiment with both.
--CELKO--
===========================
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in your
schema are.
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
- Next message: Aaron [SQL Server MVP]: "Re: CAST and CONVERT question - 24 hour time"
- Previous message: Partha Mandayam: "Re: AutoNumber Column and ..."
- In reply to: student: "Alternative for TOP"
- Next in thread: student: "Re: Alternative for TOP"
- Reply: student: "Re: Alternative for TOP"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|