0

以下是我的查询。处理过程需要 12 秒。我已经创建了 的索引,但由于和T.DataViewId,它仍然需要很长时间。提前致谢。Count(distinct())Sum

;WITH my_cte 
     AS (SELECT T.name                               AS name, 
                T.id                                 AS id, 
                Count(DISTINCT( DD.dynamictableid )) AS counts, 
                Round(Sum(D.[employees]), 0)         AS measure1 
         FROM   dbo.treehierarchy T 
                LEFT JOIN dbo.dynamicdatatableid DD 
                       ON T.id = DD.hierarchyid 
                          AND T.dataviewid = DD.dataviewid 
                LEFT JOIN dbo.demo1 D 
                       ON D.[demo1id] = DD.dynamictableid 
         WHERE  T.dataviewid = 2 
                AND T.parentid = 0 
         GROUP  BY T.id, 
                   T.name) 
SELECT name, id, counts, row_num, measure1 
FROM   (SELECT name, 
               id, 
               counts, 
               Row_number() 
                 OVER( 
                   ORDER BY counts DESC) AS row_num, 
               measure1 
        FROM   my_cte) innertable 
WHERE  ( row_num BETWEEN 1 AND 15 ) 
4

1 回答 1

1

看起来您只需要降序计数的前 15 条记录。可以像这样简单地完成:

SELECT 
TOP 15  T.name  AS name, 
        T.id    AS id, 
        Count(DISTINCT( DD.dynamictableid )) AS counts, 
        Round(Sum(D.[employees]), 0)  AS measure1 
FROM   
dbo.treehierarchy T 
LEFT JOIN 
dbo.dynamicdatatableid DD 
ON 
T.id = DD.hierarchyid 
AND 
T.dataviewid = DD.dataviewid 
LEFT JOIN 
dbo.demo1 D 
ON 
D.[demo1id] = DD.dynamictableid 
WHERE  
T.dataviewid = 2 
AND 
T.parentid = 0 
GROUP  BY 
T.id,T.name
ORDER BY
3 DESC
于 2013-05-24T20:10:21.803 回答