2010-04-16 69 views
1

我有一個返回正確的結果集的查詢,使用SQL 2005年,是如下:進一步篩選SQL結果

 
select 
    case 
    when convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) = '1969 Q4' then '2009 Q2' 
    else convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) 
    end as [Quarter], 
    bugtypes.bugtypename, 
    count(bug.bugid) as [Total] 
from bug left outer join bugtypes on bug.crntbugtypeid = bugtypes.bugtypeid and bug.projectid = bugtypes.projectid 
where 
    (bug.projectid = 44 
    and bug.currentowner in (-1000000031,-1000000045) 
    and bug.crntplatformid in (42,37,25,14)) 
or 
    (bug.projectid = 44 
    and bug.currentowner in (select memberid from groupmembers where projectid = 44 and groupid in (87,88)) 
    and bug.crntplatformid in (42,37,25,14)) 

group by 
    case 
    when convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) = '1969 Q4' then '2009 Q2' else convert(varchar(4),datepart(yyyy,bug.datecreated),101)+ ' Q' +convert(varchar(2),datepart(qq,bug.datecreated),101) 
    end, 
    bugtypes.bugtypename 
order by 1,3 desc 

它生產的年和季度的一個很好的分組名單,相關的描述符,以及按降序計數的事件計數。我想要做的就是進一步過濾,以便每個季度只顯示10個最常提交的事件。

我正在努力的是如何採取這個結果集,並實現這一點。

+0

也許爲了通過柱3(總計)和降序添加一個類WHERE ROWNUM <= 10(如果甲骨文)或LIMIT 10如果MySQL? – 2010-04-16 18:22:07

+0

使用SQL Server 2005 – 2010-04-16 18:30:10

+0

那將是前10名 – BlackICE 2010-04-16 18:30:46

回答

5

您已按Quarter和Total訂購。你是否嘗試過使用:

SELECT TOP 10 

.....查詢

編輯的休息:閱讀您的評論後,我意識到,你需要使用RANK and Partition,使這項工作。您可以在CTE包裹如下圖所示:

;WITH IncidentsTable AS 
(
    ... Insert Your Query here ... 
) 
SELECT * FROM 
(
    SELECT [Quarter], 
     BugTypeName, 
     Total, 
     Rank() OVER (Partition BY [Quarter] order by Total DESC) AS Ranking 
    FROM 
    IncidentsTable 
) 
WHERE 
    Ranking <= 10 
ORDER BY 
     Quarter, Total; 
+0

這只是要返回10條記錄,我想每個季度的前10條記錄。所以如果有15個季度,我想要返回150個記錄,每個記錄前10個。 – 2010-04-16 18:28:31

+0

我喜歡這個結構,它比嘗試將我的查詢插入Alex K's更清潔一點。 – 2010-04-16 19:23:04

1

像這樣的格局將做到這一點(分區和數量每個季度無視數< = 10):

SELECT * FROM (
    SELECT Qtr, fld, 
    ROW_NUMBER() OVER(PARTITION BY Qtr ORDER BY fld) as RN 
    FROM tbl 
) AS T 
WHERE RN <= 10 
ORDER BY Qtr 

NTILE(10)可能會做也。

+0

這很接近,我用Rank()替換了Row_Number(),它工作。 – 2010-04-16 19:20:20

0

可以使用秩和分區

Select * From 
(
    Select *, Rank() over (Partition BY qtr order by qtr, id) as Rank 
    From 
    (
       Select 1 as id, 1 as qtr,'hello' as msg 
    union all select 2, 1,'hello' 
    union all select 3,1,'hello' 
    union all select 4,1,'hello' 
    union all select 5,1,'hello' 
    union all select 6,2,'hello' 
    union all select 7,2,'hello' 
    union all select 8,2,'hello' 
    union all select 9,2,'hello' 
    union all select 10,2,'hello' 
    ) BaseQuery 
)QryWithRank 
where rank <= 2