如何按州查找一个国家的第三大人口

时间:2019-05-07 12:52:13

标签: sql sql-server ssms

我有一个表,其中有三列邮政编码,州,total_population。

ZIPCODE STATE   POPULATION
11937   36  15511
11941   36  1822
11940   36  4933
12435   36  280
12063   36  441
64733   29  1251
64734   29  1952
64735   29  13653

我正在寻找

zipcode state third_highest_population
11941  36     1822
4733   29     1251

我想不出一种方法来找到每个州的第三大人口。.非常感谢任何帮助

3 个答案:

答案 0 :(得分:1)

您可以使用窗口功能帮助按州对邮政编码人群进行排名,然后将每个州的排名保持在第三位。

SELECT *
FROM (
   SELECT zipcode, 
      state, 
      total_population, 
      DENSE_RANK() OVER (PARTITION BY state ORDER BY total_population DESC) as ziprank
   FROM yourtable
) r
WHERE ziprank = 3

RANK()DENSE_RANK()ROW_NUMBER()可能在这里都可以工作,具体取决于您的数据。 DENSE_RANK()确保您至少获得1(但可能更多)的排名3。您获得更多信息的原因是,如果两个邮政编码在该州共享同一人口。不过,这不太可能,因此DENSE_RANK()很合适。

答案 1 :(得分:1)

类似的东西:

select * from (
    select  your_table.*,  rank() over(partition by state order by totpop) rnk from your_table
) t
where 
rnk = 3

答案 2 :(得分:0)

样本数据

DECLARE @Data AS TABLE (zipcode INT, 
                        [state] VARCHAR(10), 
                        [total_population] INT
                        )
INSERT INTO @Data
SELECT 500010,'Ap',24524540 UNION ALL
SELECT 500020,'KA',47857441 UNION ALL
SELECT 500030,'TN',89456655 UNION ALL
SELECT 500040,'KL',45775475 UNION ALL
SELECT 500050,'UP',47411189 

DECLARE @N INT = 3 -- Specify highest total as you required

使用与Co相关的子查询

SELECT * FROM @Data
Go
SELECT zipcode, 
       [state], 
       [total_population]
FROM @Data e1
WHERE @N-1 = ( SELECT COUNT(DISTINCT [total_population]) 
              FROM @Data e2
              WHERE e2.[total_population] > e1.[total_population] )