Sql 如何在条件结果集中设置行数?

Sql 如何在条件结果集中设置行数?,sql,sql-server,Sql,Sql Server,我想将行号作为SQL语句中结果集的排名。我跟踪了文档,但是行功能本应在上具有功能,导致了麻烦和效率低下 没有任何行编号,这是查询: select count(*) number_of_people, p.address_state state_code, a.us_state_terr state_name from person_economic_info p inner join annotated_person_info a on p.address_stat

我想将行号作为SQL语句中结果集的排名。我跟踪了文档,但是
功能本应在上具有
功能,导致了麻烦和效率低下

没有任何行编号,这是查询:

select 
    count(*) number_of_people, p.address_state state_code, a.us_state_terr state_name
from 
    person_economic_info p 
inner join
    annotated_person_info a on p.address_state = a.numeric_id
group by 
    p.address_state, a.us_state_terr
order by 
    number_of_people desc
我无法理解,如果不在SQL查询中使用两次
count(*)
,如何获得结果排名

我尝试使用以下SQL查询。这既错误又低效:

select 
    count(*) number_of_people, p.address_state state_code, a.us_state_terr state_name,
    row_number over (order by number_of_people desc) as Rank
from 
    person_economic_info p 
inner join
    annotated_person_info a on p.address_state = a.numeric_id 
group by 
    p.address_state, a.us_state_terr
我得到以下错误:

Msg 156,15级,状态1,服务器16b9151564e7,第1行
关键字“OVER”附近的语法不正确


我希望写一个语句,可以对我的结果进行排名,并为“排名”列一列。

您不能参考同级人员的列别名。在您的
行数
函数中使用
count(*)
,它应该可以正常工作

select count(*) number_of_people
      , p.address_state state_code
      , a.us_state_terr state_name
      , ROW_NUMBER() OVER(order by count(*) desc) AS [Rank] 
from person_economic_info p 
inner join annotated_person_info a on p.address_state = a.numeric_id 
group by p.address_state, a.us_state_terr
为了避免使用计数(*)两次,您可以首先创建一个CTE并使用它创建排名:

with cte as (
select count(*) number_of_people
      , p.address_state state_code
      , a.us_state_terr state_name 
from person_economic_info p 
    inner join annotated_person_info a on p.address_state = a.numeric_id 
group by p.address_state, a.us_state_terr
)
select   c.state_code
        ,c.state_name
        ,c.number_of_people
        ,ROW_NUMBER() OVER(order by c.number_of_people desc) AS [Rank] 
from cte as c

这不会调用
count()
两次吗?您可以查看查询执行计划以了解这一点。
ROW\u NUMBER()
,而不是
ROW\u NUMBER
,顺便说一句。