简体   繁体   中英

How to return total number of records with TOP * select

I have over 300 000 rows, I would like to return total number of the records even if I pick only 20/50/100 records using TOP * statement.

Is it possible to filter select like

select top 50 * from table where rule1=rule1 and rule=rule2

Let's say that total number of records if database is 300 000 and select above would return 4 000 records. But physically it will return only 50 records, I need to know how manu is there in database using this where statement (it would return 4000).

Thanks

select top 50 *, count(*) over()
from table
where rule1=rule1 and rule=rule2

There are a lot of simple answers to this question, as other posters have pointed out. There is also a lot of subtlety depending on your scenario. There is a fairly in depth discussion of the issue @ Efficient way of getting @@rowcount from a query using row_number

SELECT TOP 50 
  * 
FROM TableName t1
INNER JOIN (SELECT 
              COUNT(*) AS CountOfRecords 
            FROM TableName) t2 on 1=1

You could do:

select top 50 *, (select count(*) from table) 
from table 
where rule1=rule1 and rule=rule2

This will give you the total number of rows as an extra column against each row returned by the main query. Not sure of the performance implications on this though...

Wasn't clear from your question if you need the count to be based on the filtered number of rows or not, but if so:

select top 50 *, (select count(*) from table where rule1=rule1 and rule=rule2) 
from table 
where rule1=rule1 and rule=rule2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM