Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 TOP and Count in the same statement

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2001-12-17 : 09:08:12
Greg writes "Hey there the following is a simplified query that contains both a Top and Count. Is this the best way to do this, or is there a way to do it as fast, with out a sub query?


SELECT COUNT(*) AS CNT
FROM (SELECT TOP 50 PERCENT
FROM Person) AS T"

Arnold Fribble
Yak-finder General

1961 Posts

Posted - 2001-12-17 : 10:00:35
SELECT COUNT(*)/2 FROM Person


Go to Top of Page

Pick
Starting Member

3 Posts

Posted - 2001-12-26 : 12:23:14
But what if the SQL is being built automatically and the only thing that you can change from call to call is the %?


Go to Top of Page

aclarke
Posting Yak Master

133 Posts

Posted - 2001-12-26 : 12:55:54
What are you trying to do? Find out what n% of count(*) is? You could do something like this:


select count(*) * @pct / 100 as cnt from person


Edit: Hmm after posting I realized that was essentially what Arnold Fribble had written. So I'm not sure what the problem is. Or you could just do what A.F. suggested if you don't like my small change and just find out n% programmatically either later on in your stored procedure or back in your application code, whatever works best for you.

Edited by - aclarke on 12/26/2001 12:58:19
Go to Top of Page

Pick
Starting Member

3 Posts

Posted - 2001-12-31 : 15:28:53
Here is a better example of what I am trying. If there is a more efficient way to do this I would be glad to know it.

@pct is a number from 0 to 100 that is passed in

ORIGINAL:
SELECT Count(*) FROM (SELECT TOP @pct PERCENT * FROM Person) AS P

The original is what I am using in production currently, but I was looking for a way to do it with out a sub-query.

Way to do it with out a sub query:
SELECT convert(int, COUNT(*) * (@pct * .01)) FROM Person

Thanks for the suggestions!

Go to Top of Page
   

- Advertisement -