aBoy
aBoy

Reputation: 35

Query returning a row with one column's max value

I have two columns, City and Population. The goal of this query is to return the single row that has the City with the highest population. I have virtually no experience with SQL Server or databases or queries, as i'm currently in my first programming class ever. This database is linked to a program I'm creating with C# and Visual Studio. I've tried a handful of things such as:

SELECT City, Population FROM dbo.[Table] WHERE Population = Max(Population)

or

SELECT City, Max(Population) FROM dbo.[Table]

or

SELECT City, Population FROM dbo.[Table] ORDER BY Population Desc
SELECT TOP 1 * FROM dbo.[Table]

I feel like the answer is simple but going over my head nonetheless.

SELECT Max(Population) FROM dbo.[Table]

^^^ With this i was able to return only the maximum population but I need the city to return with it.

Upvotes: 0

Views: 40

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269873

You are almost there with the middle approach:

SELECT TOP 1 City, Population
FROM dbo.[Table]
ORDER BY Population Desc;

If you want ties as well:

SELECT TOP (1) WITH TIES City, Population
FROM dbo.[Table]
ORDER BY Population Desc;

Upvotes: 1

Related Questions