Get Most Recent Date in Query

Mark_Didrikson
ServiceNow Employee
ServiceNow Employee

Hello,

I am trying to write a query to pull back the most recent date (MAX) from a table. The query is not working.

What is the way to query to give you the most recent date value (sys_created_on)?



var count = new GlideAggregate('kb_use');
count.addQuery('article', '10a274a9048599009433ce3847235f89');
count.addQuery('used',true);
count.addAggregate('MAX', 'sys_created_on');
var max = 0;
while (count.next()) {
gs.print('next: ' + count.sys_created_on);
max = count.getAggregate('MAX', 'sys_created_on');

}
gs.print("MAX Date: " + max);


Thanks!

3 REPLIES 3

Jim Coyne
Kilo Patron

The following code will return the last record created for that particular condition:



var count = new GlideRecord('kb_use');
count.addQuery('article', '10a274a9048599009433ce3847235f89');
count.addQuery('used',true);
count.orderByDesc('sys_created_on');
count.setLimit(1);
count.query();
if (count.next()) {
gs.print(count.getValue("sys_created_on"));
gs.print(count.getDisplayValue("sys_created_on"));
}


Ordering it by the sys_created_on and then limiting it to just 1 record does the trick. And the bonus is you have access to the entire record if you need it. The "getDisplayValue" returns it to you in your current timezone.


Thanks...


Mark_Didrikson
ServiceNow Employee
ServiceNow Employee

Thanks! Works great!