How to Get Item with Max Id

How to get item with max id?

Filters alone cannot do what you're after as they only consider a single top-level object at a time.

Beyond that conceptual issue, there are a few issues with the code you posted:

  1. @"@max.id" is not a valid NSPredicate format string. NSPredicate format strings must be composed of comparisons between expressions, not expressions on their own.

  2. Collection operators such as @max must be applied to a collection. In your example it is being applied to an Entity. Since an Entity is not a collection, the predicate would not be valid. It would be valid to apply a collection operator to a List property on Entity though.

Something like the following should do what you're after:

let entities = realm.objects(Entity)
let id = entities.max("id") as Int?
let entity = id != nil ? entities.filter("id == %@", id!).first : nil

Select only one Product with MAX(Id) for each Date

there are many ways to do the same, one of those is to use a row_number function

WITH C AS(
SELECT Date
, Client
, ProductCode
, Price
, ROW_NUMBER() OVER(PARTITION DATE, FOLIO, PRODUCTCODE ORDER BY ID DESC) AS RN
From myTable
)
SELECT Date
, Client
, ProductCode
, Price
FROM C
WHERE RN = 1

What you have to do in this case is create a CTE(It works like a subquery but more readeable) then apply row_number and partition your rows by date,folio,productcode and order it by id, this is going to return you your current list with a rn then filter rn, something good about this is that rn for each case are not repeating.

How can I select the row with the highest ID in MySQL?

SELECT * FROM permlog ORDER BY id DESC LIMIT 0, 1

How do I get the max ID with Linq to Entity?

Do that like this

db.Users.OrderByDescending(u => u.UserId).FirstOrDefault();

How can I get a value in a Listobject by highest Id?

Ordering the entire sequence costs O(n*log(n)), and it's not really needed if all you want is the max of your collection.

You can find the max in O(n) just by iterating over the sequence, and keeping track of the maximum element that you have encountered. You might even create an extension method to do it for you, or just do it using LINQ:

var result = yourcollection.Aggregate((x,y) => x.IdDate > y.IdDate ? x : y);

you can find many more examples here



Related Topics



Leave a reply



Submit