Help with a Count Distinct Script

Rohit8
Tera Expert

Hello,

I am have created an indicator to get a total count of users. The table has a lot of users appearing multiple times. So I need to do a count distinct to get a total count of unique "user_name" records. I am not that proficient in Javascript yet. 

This is the script I added:

var ga = new GlideAggregate('u_removable_media_exception_request');
ga.addAggregate('COUNT(DISTINCT', 'user_name');
ga.setGroup(false);
ga.query();
ga.next();
gs.info(ga.getAggregate('COUNT(DISTINCT', 'user_name'));

find_real_file.png

And I keep getting the below error during Job collection. It fails and collects 0 records.

 

find_real_file.png

 

Could you guys help me find out what am I doing wrong or suggest a better way to do this.

Thanks a lot.

 

1 ACCEPTED SOLUTION

Adam Stout
ServiceNow Employee
ServiceNow Employee

Let's solve that problem then.  Use a COUNT Distinct and for the script, just put in the fully qualified field name.  Select the argument for the script to be the field you want to count distinct (Requestor.User Name?)

 

Then your script will be one line (I'm guessing on the field names, so double check that):

current.requestor.user_name

That should do the trick.  This allows you to do aggregates on dot walked fields.

View solution in original post

8 REPLIES 8

Shashikant Yada
Tera Guru

You can use below code:

var ga = new GlideAggregate('u_removable_media_exception_request');
ga.addAggregate('count');
ga.addAggregate('count(distinct','user_name');
ga.setGroup(false);
ga.query();
ga.next();
gs.info(
gs.info(agg.getAggregate('count(distinct','user_name')));

Thanks
Shashikant

Hit Helpful or Correct on the impact of response.

Thank you, I tried it and got error about agg not defined.

 

Adam Stout
ServiceNow Employee
ServiceNow Employee

Why aren't you just setting the indicator to do a COUNT distinct?  Why do you need a script?  Is this the whole script? Since there is no query, you will get the same answer for every row.  I'm not sure of your use case, but this seems like it will return garbage and do it with poor performance.

The last line needs to evaluate to a number.  gs.info returns void which is why you are getting undefined.

Thanks, Adam. I am after the user_name field which shows when you drill down into the "Requestor Name". This is because the Requestor Name is like "Display name" which is common but user_name is unique. But the field in the indicator form doesn't allow me go deeper unlike reporting where you have the option of "Show Related fields".

 

find_real_file.png

 

I could be doing it wrong, please let me know if there is an alternate to achieve this.