Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find max value in table column

Tags:

grails

I am creating a version control domain class in Grails:

class VersionControl {

    Date dateCreated
    Long versionNumber

    Long getLatestVersionNumber() {
        //return largest versionNumber
    }

}

I would like to add a query to get the largest version number stored:

Long getLatestVersionNumber()

In SQL this query would look more or less as follows:

SELECT TOP 1 MAX(versionNumber) FROM VersionControl

The function MUST return the value as a long.

What is the correct way to do this in Grails?

like image 936
Chopo87 Avatar asked Oct 08 '12 14:10

Chopo87


People also ask

How find Max from table in SQL?

The SQL MIN() and MAX() Functions The MIN() function returns the smallest value of the selected column. The MAX() function returns the largest value of the selected column.

Can we use Max on a column?

The MAX() function can be used on the string column. For example, the following uses the MAX() function on the LastName column of the Employee table. It will sort the column alphabetically and the last value will be returned.

What is the maximum value in the price column of the Car_info table?

5. What is the maximum value in the price column of the car_info table? Correct: To ensure that the values in the price column fell within the expected range, you used the MIN and MAX functions to determine that the maximum price was 45, 400.


2 Answers

You can use GORM criteria, querying with projections:

VersionControl.createCriteria().get {
    projections {
        max "versionNumber"
    }
} as Long
like image 98
Arturo Herrero Avatar answered Oct 10 '22 20:10

Arturo Herrero


VersionControl.executeQuery("select max(versionNumber) from VersionControl")

This is easier for me to understand.

like image 6
Shawn Avatar answered Oct 10 '22 22:10

Shawn