2011-06-18 64 views
1

我知道TSQL相當不錯,但我在這裏肯定會碰壁。複雜的TSQL查詢(Top n和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遞減劑前20行到我的組?

如果只有15行,它應該只是基於這些。

回答

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 ... 
+0

我只是用了幾個修改了它的where子句我在最終查詢問題忘了,它就像一個魅力!非常感謝!! – MathiasH