选择行,直到count_visitor列的总和小于25

时间:2015-03-16 12:02:52

标签: c# sql asp.net sql-server

visitor_keyword                    count_visitor

Homepage                                14
Web developing                           6
Page Mobile application                  4
Developing websites for ipad             3
Android developing                       2
Android developing in new hampshire      2
Android development                      2

我希望输出到count_visitor列的总和是第一行的25

ie:我们得到的输出只有前3位

我的SQL查询是

select visitor_keyword, COUNT(visitor_keyword) AS count_visitor
from handlegraph
group by visitor_keyword
order by count_visitor DESC

3 个答案:

答案 0 :(得分:0)

然后您应该使用having关键字。

select visitor_keyword, COUNT(visitor_keyword) AS count_visitor
from handlegraph
group by visitor_keyword
having count(visitor_keyword) < 25
order by visitor_keyword DESC

答案 1 :(得分:0)

我认为,在执行GROUP BY之后,您希望将所有组返回到SUM聚合count_visitor达到25的点。如果您使用的是SQL Server 2012 +,您可以使用SUM() OVER()来计算count_visitor的累计总数:

;WITH CTE AS (
   SELECT visitor_keyword, COUNT(visitor_keyword) AS count_visitor
   FROM handlegraph
   GROUP BY visitor_keyword
)
SELECT *
FROM (
   SELECT visitor_keyword, count_visitor, 
          SUM(count_visitor) OVER (ORDER BY count_visitor DESC) AS s
   FROM CTE ) t
WHERE t.s < 25
ORDER BY count_visitor DESC

您可以对SQL SERVER 2008 R2或更早版本使用以下查询:

;WITH CTE AS (
   SELECT visitor_keyword, 
          COUNT(visitor_keyword) AS count_visitor, 
          ROW_NUMBER() OVER (ORDER BY COUNT(visitor_keyword) DESC) AS rn
   FROM handlegraph
   GROUP BY visitor_keyword
)
SELECT *
FROM (
   SELECT visitor_keyword, count_visitor, (SELECT SUM(count_visitor) 
                                           FROM CTE c2
                                           WHERE c2.rn <= c1.rn) AS s
   FROM CTE AS c1 ) t
WHERE t.s < 25
ORDER BY count_visitor DESC

答案 2 :(得分:0)

我认为它会帮助你......

当总和超过25

时,它将限制数据
with cte_a as
(

 select visitor_keyword   from handlegraph
)

select sum(tbl2.count_visitor), visitor_keyword 
from cte_c as tbl1
inner join handlegraph as tbl2
on tbl2.visitor_keyword   =tbl1.visitor_keyword   
group by tbl1.visitor_keyword   
having sum(tbl2.count_visitor)<25