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

Bijaya Khadka picture Bijaya Khadka · Sep 18, 2013 · Viewed 37k times · Source

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 ..

Answer

TechDo picture TechDo · Sep 18, 2013

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