复杂的TSQL查询(前n个和组合的组合)

时间:2011-06-18 13:49:25

标签: sql tsql

我非常了解TSQL,但我肯定会在这里碰壁。

我正在对一些代理进行一些统计,我使用group by来构建这样的数据:

    select 
    AgentID, 
    [No 14] as answer_option, 
    COUNT(*) as amount_of_answers, 
    CASE 
        WHEN [No 14] = 1 then CONVERT(int, COUNT(*), 1) * 5 
        WHEN [No 14] = 2 then CONVERT(int, COUNT(*), 1) * 4 
        WHEN [No 14] = 3 then CONVERT(int, COUNT(*), 1) * 3 
        WHEN [No 14] = 4 then CONVERT(int, COUNT(*), 1) * 2 
        WHEN [No 14] = 5 then CONVERT(int, COUNT(*), 1) * 1 
        END as combined_weight
from #temptable
where 
[No 14] <> '-'
and AgentID <> '-1'
group by AgentID, [No 14]
order by AgentID, svar

现在这一切都很有效,直到我被告知数据应该只基于每个代理的最后20个输入行。

代理的最后20行可以这样找到:

select TOP 20 * from #temptable where AgentID = X order by changedDate desc

如何组合这两个查询,以便我只根据查询中的ChangedDate desc将每个代理的前20行获取到我的组中?

如果只有15行,则应该基于这些行。

1 个答案:

答案 0 :(得分:3)

您可以使用row_number()过滤掉每个代理的最后20行。变化:

from #temptable

为:

from    (
        select  row_number() over (partition by AgentID 
                                   order by ChangedDate desc) as rn
        ,       *
        from    #temptable
        ) as SubQueryAlias
where   rn <= 20
        and ...