简体   繁体   中英

Total Row Count in sql query---sql server 2008

My query is as follows

BEGIN

    WITH MyCTE
    AS (
        SELECT T.MusicAlbumTitle
            ,D.musicTitle
            ,D.mVideoID
            ,D.musicFileName
            ,T.ReleaseDate AS ReleasedDate
            ,D.MusicLength
            ,D.musicSinger
            ,D.MusicVideoID
            ,D.ExternalLink             
            ,D.CoverImg             
            ,ROW_NUMBER() OVER (
                PARTITION BY D.MusicVideoID ORDER BY D.mVideoID
                ) AS row_num
        FROM dbo.Music_Video T
        JOIN dbo.Music_Video_Details D ON T.MusicVideoID = D.MusicVideoID
        WHERE T.PortalID = @PortalID
            AND T.CultureCode = @CultureCode
            AND T.ComingSoon <> 1
        GROUP BY T.MusicAlbumTitle
            ,D.musicTitle
            ,D.mVideoID
            ,T.ReleaseDate
            ,D.musicFileName
            ,D.MusicLength
            ,D.musicSinger
            ,D.MusicVideoID
            ,D.ExternalLink
            ,D.CoverImg
        )   
    SELECT a.mVideoID
        ,a.MusicVideoID
        ,a.musicFileName            
        ,a.MusicAlbumTitle
        ,a.ReleasedDate
        ,a.row_num
        ,a.CoverImg
        ,a.ExternalLink         
        ,a.musicTitle
        ,a.MusicLength                  
    FROM MyCTE a            
    WHERE row_num = 1
    ORDER BY MusicVideoID DESC
END

I need to achieve total row count from last select statement. which mean total row count that is being selected.

or any idea that might be use in this condition

How can i do this ..

Please add COUNT(*) OVER() in your select, which returns total rows selected as a new column. Ex:

SELECT 
    *, 
    COUNT(*) OVER() AS [Total_Rows] 
FROM YourTable

Just to be clear, you need to add the count to the CTE, not the outer query. The outer select is returning only one row, so the count would always be one.

The CTE should start:

WITH MyCTE
AS (
    SELECT T.MusicAlbumTitle
        ,D.musicTitle
        ,D.mVideoID
        ,D.musicFileName
        ,T.ReleaseDate AS ReleasedDate
        ,D.MusicLength
        ,D.musicSinger
        ,D.MusicVideoID
        ,D.ExternalLink             
        ,D.CoverImg             
        ,ROW_NUMBER() OVER (
            PARTITION BY D.MusicVideoID ORDER BY D.mVideoID
            ) AS row_num,
        COUNT(*) over () as total_count

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