简体   繁体   中英

SQL paging a query that has a group by clause

Is it possible to do a paging type of query where my main query has a group by clause in it.

How would I implement this (if this is even possible)

Example query:

SELECT * FROM TABLE_NAME GROUP BY DATEPART(YEAR,DATE), DATEPART(YEAR,MONTH)

Can I possibly get the result via reading it page by page?

...and while on the topic, can I also get the total number of rows that would be retrieved without putting it inside a sub query?

Use ROW_NUMBER & CTE feature of SQL Server as mentioned below.

WITH CTE AS (
SELECT     A,B,C
           ROW_NUMBER() OVER (ORDER BY  columnName) RN
)
SELECT * FROM CTE WHERE RN Between 1 and 10

Please refer http://sqlserverplanet.com/sql/pagination-using-rownumber for more details.

The concept of pagination is :

  1. You need to get the total number of rows.

    SELECT * FROM table_name where id='id';

  2. Set the number of items to be show per page. Like $limit=50. This mean, you will show 50 items per page.

Hmm, I think it should be better if you'll take a look at this one, http://php.about.com/od/phpwithmysql/ss/php_pagination.htm . It's explained much more better.

Hope that helps.

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