在达到特定值之前计算SQL结果中的记录数

时间:2019-04-11 20:49:08

标签: sql vbscript count record clause

试图计算SQL记录的数量,直到达到表列之一中的某个值为止。使用Asp / VBscript。

不确定如何制定查询条件。

我尝试过的是,但是当然没有用。我想要的是按“点”列以降序排列结果,并按city_id“ 12500”分组。然后,我需要计数记录的数量,直到匹配特定的“ member_id”为止。一些“点”值也可能相同,这可能导致计数错误。相似点的值应忽略。

名为“ rankings”的数据库如下所示:

id  |  member_id  |  city_id  |  points
1   |      1      |   12500   |    2
3   |      2      |   12500   |    5
4   |     34      |     800   |    1
5   |     14      |   12500   |    14
6   |      6      |     600   |    12
7   |     11      |   12500   |    11
8   |     12      |   12500   |    5

例如,如果我想查找恰好属于city_id“ 12500”的member_id“ 2”的排名,则Count函数的正确最终值应为3。这是因为member_id“ 2”具有即使考虑到member_id为“ 12”的积分,也要在city_id“ 12500”中获得第三高的积分值。

以下是我能想到的一切,因为我无论如何都不是专业人士,而且我知道它缺少很多!

member_id = 2
city_id = 12500

SELECT Count() as city_ranking FROM (SELECT * from rankings WHERE city_id='"&city_id&"' AND member_id <> '"&member_id&"' ORDER BY points DESC)

2 个答案:

答案 0 :(得分:0)

DENSE_RANK函数可以为您解决问题!

SELECT *, DENSE_RANK() OVER (PARTITION BY city_ID ORDER BY points DESC) AS columnAliasOfYourChoice FROM TABLE

答案 1 :(得分:0)

您可以通过执行以下操作来获得特定成员的排名:

select count(distinct points)
from ranking r cross join
     (select r.*
      from ranking r
      where member_id = 5
     ) rm
where r.points >= rm.points and
      r.city_id = rm.city_id;

尽管您可以使用窗口函数来表达这一点,但它有点烦躁,因为您必须注意放置过滤器的位置。