使用 ORDER BY 在 SQL 中记录 COUNT,直到在列中找到特定值
RECORD COUNT in SQL with an ORDER BY, until a specific value is found in a column
我正在尝试从记录集中获取行数。
我想要计算记录集中的行数,按名为 member_location
的列中的公共值分组,按名为 reputation_total_points
的列降序排列, 直到解析器在 ID
列中得到具有特定值的结果。
例如,如果查询使用 member_location
= 10,并且 id
= 2,使用下面的信息,最终正确的计数结果将是3。以下是数据库条目的示例:
Columns: id | reputation_total_points | member_location
2 | 32 | 10
3 | 35 | 7
4 | 40 | 10
5 | 15 | 5
6 | 10 | 10
7 | 65 | 10
听起来你想按 member_location
分组,但要排除特定的 ID。在这种情况下,你想要的是:
SELECT member_location, count(*)
FROM table_name
WHERE id <> 2
GROUP BY member_location
对于您的输入,这将 return:
member_location count(*)
5 1
7 1
10 3
如果我理解正确,这应该会按预期工作:
SELECT rn
FROM
(
SELECT id
,ROW_NUMBER() -- assign a sequence based on descending order
OVER (ORDER BY reputation_total_points DESC) AS rn
FROM tab
WHERE member_location = 10
) AS dt
WHERE id = 2 -- find the matching id
事实上,这看起来像是您想对您的会员进行排名:
SELECT id
,RANK()
OVER (PARTITION BY member_location
ORDER BY reputation_total_points DESC) AS rnk
FROM tab
我不确定你的 where 是否同时使用 id 和 member_location,因为 id = 2 只会返回一行。但是,如果您只是在 member_location = 10 出现之后,那么类似下面的内容应该有效:
SELECT
member_location,
COUNT(member_location) AS [Total]
FROM yourTable
GROUP BY member_location
希望这是有道理的!
我想这就是你想要的,但我不明白你为什么需要分组。
DECLARE @id int = 2
SELECT member_location, COUNT(*) AS cnt
FROM <table_name>
WHERE reputation_total_points >= (SELECT reputation_total_points FROM <table_name> WHERE id = @id)
AND id <> @id
GROUP BY member_location
我正在尝试从记录集中获取行数。
我想要计算记录集中的行数,按名为 member_location
的列中的公共值分组,按名为 reputation_total_points
的列降序排列, 直到解析器在 ID
列中得到具有特定值的结果。
例如,如果查询使用 member_location
= 10,并且 id
= 2,使用下面的信息,最终正确的计数结果将是3。以下是数据库条目的示例:
Columns: id | reputation_total_points | member_location
2 | 32 | 10
3 | 35 | 7
4 | 40 | 10
5 | 15 | 5
6 | 10 | 10
7 | 65 | 10
听起来你想按 member_location
分组,但要排除特定的 ID。在这种情况下,你想要的是:
SELECT member_location, count(*)
FROM table_name
WHERE id <> 2
GROUP BY member_location
对于您的输入,这将 return:
member_location count(*)
5 1
7 1
10 3
如果我理解正确,这应该会按预期工作:
SELECT rn
FROM
(
SELECT id
,ROW_NUMBER() -- assign a sequence based on descending order
OVER (ORDER BY reputation_total_points DESC) AS rn
FROM tab
WHERE member_location = 10
) AS dt
WHERE id = 2 -- find the matching id
事实上,这看起来像是您想对您的会员进行排名:
SELECT id
,RANK()
OVER (PARTITION BY member_location
ORDER BY reputation_total_points DESC) AS rnk
FROM tab
我不确定你的 where 是否同时使用 id 和 member_location,因为 id = 2 只会返回一行。但是,如果您只是在 member_location = 10 出现之后,那么类似下面的内容应该有效:
SELECT
member_location,
COUNT(member_location) AS [Total]
FROM yourTable
GROUP BY member_location
希望这是有道理的!
我想这就是你想要的,但我不明白你为什么需要分组。
DECLARE @id int = 2
SELECT member_location, COUNT(*) AS cnt
FROM <table_name>
WHERE reputation_total_points >= (SELECT reputation_total_points FROM <table_name> WHERE id = @id)
AND id <> @id
GROUP BY member_location