How to reference one CTE twice?

后端 未结 5 1453
粉色の甜心
粉色の甜心 2020-12-15 17:44

I have a very fat common table expression which includes row numbers so that I can return a paged result set. I also want to return the total number of records that match th

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 18:30

    You can use commas to create multiple CTEs that references the CTEs Above.

    Just to illustrate what I mean:

    with recs as (
    select 
        *, 
        row_number() over (order by id) as rownum from ......
        ),
    counts as (
        select count(*) as totalrows from recs
    )
    select recs.*,count.totalrows
    from recs
    cross apply counts 
    where rownum between @a and @b .... 
    

    This is not the a good solution.

    The best solution I found to have the total count in a CTE without counting the records is described in this article.

    DECLARE @startRow INT; SET @startrow = 50;
    WITH cols
    AS
    (
        SELECT table_name, column_name, 
            ROW_NUMBER() OVER(ORDER BY table_name, column_name) AS seq, 
            ROW_NUMBER() OVER(ORDER BY table_name DESC, column_name desc) AS totrows
        FROM [INFORMATION_SCHEMA].columns
    )
    SELECT table_name, column_name, totrows + seq -1 as TotRows
    FROM cols
    WHERE seq BETWEEN @startRow AND @startRow + 49
    ORDERBY seq
    

提交回复
热议问题