在CTE中获取Count()会导致表扫描

时间:2017-02-24 12:03:57

标签: sql sql-server common-table-expression

我有以下查询:

;WITH CTE
AS (
    SELECT ROW_NUMBER() OVER (
            ORDER BY RTT.DAYSTOWAIT DESC
            ) AS ROW
        ,COUNT(*) OVER () AS ROWCNT
    --...
    -- ADDITIONAL COLUMNS
    --...
    FROM TABLE1 T1
    INNER JOIN TABLE2 T2 ON T1.OID = T2.OID
    INNER JOIN ORG ON T1.ORGOID = ORG.OID
    INNER JOIN EPI E ON E.OID = T1.EOID
        AND E.PKEY = T1.PKEY
        AND E.STATUS = 'A'
    INNER JOIN PATHWAY ON OID = EPI.PATHWAYOID
        AND PATHWAY.PARTKEY = T1.PARTKEY
        AND PATPATHWAY.STATUS = 'A'
    )
SELECT CTE.ROW
    ,CTE.ROWCNT
FROM CTE

当用Cte.RowCount选择Cte时,它会导致表扫描, 但当我删除" RowCount" select中的列,它工作正常(寻找)。

是否有更有效的方法来获取count()?

0 个答案:

没有答案