2013-05-22 72 views
0

以下是我的查詢。處理需要12秒。我創建了T.DataViewId的索引,但由於Count(distinct())Sum,它仍然需要很長時間。提前致謝。SQl Server 2008性能問題計數(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) 

回答

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