简体   繁体   中英

Finding the largest number in a sequence of numbers in a SQL database

Suppose I have a SQL database in which a column could look something like this

Numbers
-------
1
1
2
3
4
4

Is it possible to create a single SQL query that simply grabs the largest number, which in this case would be 4 ? Or would I have to query every single number, put them in some sort of list in an external program, and write an algorithm to find the largest one?

Use can use the MAX Aggregate function. Since your table only has one column it would look like

SELECT MAX(NUMBERS) n from yourtable

depending on your backend you could also put into a variable. For example in SQL Server

Declare @TheMax int
SELECT @TheMax = MAX(NUMBERS) 
FROM yourTable

Here's a working example on data.stackexchange.com

If you also wanted the Max Per somthing you'd need a group by

For example this query on Data.SE gives the max score per tag

SELECT 
      tagname, max(score) 
FROM 
   posts p
   INNER JOIN postTags pt
   ON p.id = pt.postId
   INNER JOIN tags t
   ON pt.tagid = t.id 
GROUP BY 
   tagname ​

x是您的列名时,则:

SELECT MAX(x) FROM numbers

这应该适用于大多数SQL服务器。

Select Max(Number) From Table

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM