进一步过滤SQL结果

时间:2010-04-16 18:18:36

标签: sql sql-server filter

我有一个使用SQL 2005返回正确结果集的查询。它如下:

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个事件。

我正在努力的是如何采用这个结果集并实现这一目标。

3 个答案:

答案 0 :(得分:5)

您已按季度和总计订购。你尝试过使用过:

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;

答案 1 :(得分:1)

像这样的模式会这样做(每个季度的分区和数字忽略数字&lt; = 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)也可能会这样做。

答案 2 :(得分: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