[英]Complex TSQL query (Top n and Group by combined)
我非常了解TSQL,但是我确实在这里碰壁。
我正在对某些Agent进行一些统计,并且使用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行,则应基于这些行。
您可以使用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 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.