简体   繁体   English

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

[英]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. 我需要从上一个select语句中获得总行数。 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. 请在您的选择中添加COUNT(*) OVER() ,这将返回选为新列的总行数。 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. 为了清楚起见,您需要将计数添加到CTE,而不是外部查询。 The outer select is returning only one row, so the count would always be one. 外部选择只返回一行,因此计数总是一行。

The CTE should start: 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM