Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

Get your favourite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved in your SSC briefcase from the favorites tab.
Download now (direct download link)

Display COUNT(*) but ONLY TOP 100

By Luigi Marinescu,

Let's say you have a result set with 5000 records but you want to display only 100 of them and in the same time to display the count of ALL records (5000).

Using next script you cand get these within ONE SINGLE STEP but not two as:
SELECT COUNT(*) FROM X
SELECT TOP 100 * FROM X

ONE STEP solution:

Let's say you have a table, ContactProperty where a Contact can have more properties:

CONTACTID PROPERTYID
1 10
1 10
2 20

So, the next script returns the top 100 UNIQUE contactidIds.

 

This is what you get:

rowno contactid
54977 4378508
54976 4378507
54975 4378495
54974 4378421
54973 43784

 

The value of RowNo from the first record represents the COUNT(*) of the whole result set, in this case I have 54977 rows but this returns only 100 of them.

This is a particular case but you can remove the "GROUP BY".

ENJOY!

Luigi

Total article views: 2412 | Views in the last 30 days: 2
 
Related Articles
FORUM

Need DateTime format and count of records

Need DateTime format and count of records

FORUM

Flat file record count inside script task

how to get Flat file record count inside script task?

FORUM

Counting records over several tables

Wanting to count the number of records in each table after a certain date

FORUM

get count of the records within specific dates

get count of the records within specific dates

SCRIPT

Count all records the tables

Count all the records from the tables that exist in a database

Tags
count(*)    
top 100    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones