sql查询中的总行数--- sql server 2008

时间:2013-09-18 10:23:48

标签: sql sql-server sql-server-2008 select rowcount

我的查询如下

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

我需要从上一个select语句中获得总行数。 这意味着正在选择的总行数。

或在这种情况下可能使用的任何想法

我该怎么做..

2 个答案:

答案 0 :(得分:12)

请在您的选择中添加COUNT(*) OVER(),这会返回选为新列的总行数。 例如:

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

答案 1 :(得分:2)

为了清楚起见,您需要将计数添加到CTE,而不是外部查询。外部选择只返回一行,因此计数总是一行。

CTE应该开始:

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