MAX query using CAML

ashwnacharya picture ashwnacharya · Feb 5, 2009 · Viewed 17.2k times · Source

I want to select a sharepoint list item which has the Maximum value for a particular column. How can I do this using CAML queries?

Answer

MagicAndi picture MagicAndi · Aug 12, 2009

The following CAML query would return the maximum value for a given column:

var maxValue;

try
{
    using (SPSite objSite = new SPSite(sSiteUrl))
    {
        using (SPWeb objWeb = objSite.OpenWeb())
        {
            SPList objList = objWeb.Lists[sListName];

            SPQuery objQuery = new SPQuery();
            objQuery.Query = "<OrderBy><FieldRef Name='ColumnName' Ascending='False' /></OrderBy><RowLimit>1</RowLimit>";
            objQuery.Folder = objList.RootFolder;

            // Execute the query against the list
            SPListItemCollection colItems = objList.GetItems(objQuery);

            if (colItems.Count > 0)
            {
                maxValue = (<Insert Appropriate Cast>) colItems[0];
            }
        }
    }
}
catch (Exception ex)
{
    ...
}

return maxValue;