开发者

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, 开发者_如何学JAVAput 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 ​


When x is your column name then:

SELECT MAX(x) FROM numbers


This should work on most SQL servers.

Select Max(Number) From Table
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜