0

My table structure looks like this:

enter image description here

I want id(primary key) of city with max population statewise.

If there is a tie in max population in particular state then any one id of those rows should be selected.

enter image description here

Brigand
  • 84,529
  • 20
  • 165
  • 173
Yasin
  • 1,150
  • 5
  • 19
  • 39

5 Answers5

3

Use window function for this:

with cte as(select *, row_number() 
                      over(partition by state order by population desc, id) rn from table)
select * from cte where rn = 1

If there can be several rows with max population then you can try rank function instead of row_number:

with cte as(select *, rank() 
                      over(partition by state order by population desc) rn from table)
select * from cte where rn = 1
Giorgi Nakeuri
  • 35,155
  • 8
  • 47
  • 75
1

required sql query:

SELECT *
FROM(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY state ORDER BY population DESC) AS RowNum
    FROM dbo.tbl_city
    ) s
WHERE s.RowNum = 1
Musakkhir Sayyed
  • 7,012
  • 13
  • 42
  • 65
0

Try this:

select id, state, population
from tbl_city a
where id = (select top 1 id from tbl_city where state = a.state order by population DESC)
0

You can try this code:

SELECT * FROM (
   SELECT id, state, population,
      ROW_NUMBER() OVER(PARTITION BY state ORDER BY population DESC) AS rn
   FROM tbl_city) AS A
WHERE rn = 1
Nguyễn Hải Triều
  • 1,454
  • 1
  • 8
  • 14
0

Try this,

SELECT id,
       state,
       population
FROM   #yourtable A
WHERE  population IN(SELECT Max(population) AS population
                     FROM   #yourtable A1
                     WHERE  A.state = A1.state
                     GROUP  BY state) 
Aj.na
  • 283
  • 2
  • 9