Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MAX query using CAML

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?

like image 744
ashwnacharya Avatar asked Feb 05 '09 14:02

ashwnacharya


3 Answers

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;
like image 124
Tangiest Avatar answered Oct 11 '22 18:10

Tangiest


<Query>
    <OrderBy>
            <FieldRef Name="particularcolumn" Ascending="FALSE" />
    </OrderBy>
</Query>
like image 11
Brian Bolton Avatar answered Oct 11 '22 20:10

Brian Bolton


This can be done ordering by this field in descending way and taking the first element of the collection returned.

like image 3
jaloplo Avatar answered Oct 11 '22 19:10

jaloplo