The CreatorCon Call for Content is officially open! Get started here.

query the last record with group by

ryuzh
Mega Contributor

hi,

I have a "order" table with below structure:

sys_id
customer_id
product
order_date
1AAAApple2016-01-05
2AAAOrange2016-09-05
3BBBBanana2017-03-05
4BBBPear2017-02-05
5CCCWatermelon2016-08-05
6CCCGrape2017-07-05

How can I query the latest order for each customer in a script, which should return:

customer_id
product
order_date
AAAOrange2016-09-05
BBBBanana2017-03-05
CCCGrape2017-07-05

Thank you

Jack

1 ACCEPTED SOLUTION

sethivarun
Kilo Guru

Hi Jack,


Following script should give you what you need



var count = new GlideAggregate('order');


count.addAggregate('COUNT');


count.groupBy('customer_id');


count.query();


while (count.next()) {  


var customer = count.customer_id.getDisplayValue();


var customerLatest= new GlideRecord('order');


customerLatest.addQuery('customer_id',customer );


customerLatest.setLimit(1);


customerLatest.orderByDesc('order_date');


customerLatest.query();


if(customerLatest.next()){


gs.print(customerLatest.customer_id +"   " + customerLatest.product + " " + customerLatest.order_date );


}


}





Please mark it as correct if it answers your question


View solution in original post

4 REPLIES 4

sethivarun
Kilo Guru

Hi Jack,


Following script should give you what you need



var count = new GlideAggregate('order');


count.addAggregate('COUNT');


count.groupBy('customer_id');


count.query();


while (count.next()) {  


var customer = count.customer_id.getDisplayValue();


var customerLatest= new GlideRecord('order');


customerLatest.addQuery('customer_id',customer );


customerLatest.setLimit(1);


customerLatest.orderByDesc('order_date');


customerLatest.query();


if(customerLatest.next()){


gs.print(customerLatest.customer_id +"   " + customerLatest.product + " " + customerLatest.order_date );


}


}





Please mark it as correct if it answers your question


ryuzh
Mega Contributor

Thank you Varun. I think we have to do it in two queries. but it works.



Thanks again


Narayana1
Tera Contributor

Thank you for posting the script and your comments. Would anyone happen to know why I see only records with no value (in the equivalent of customer_id field mentioned here) when I add the script include as filter on a report? Say i named this script include 'Xyz', my filter condition on the report was customer_id.sys_id  'is one of'  javascript: Xyz().

did you figure it out eventually?