Splunk Search

How to calculate percentages with multiple count function?

homer07
Explorer

I'm trying to calculate percentages based on the number of events per vary group. There are actually a lot of events, so can't use method like count(eval(...)). The summary of events is as follows:

 

 

 

color
------
green
red
greed
greed
red

 

 

 

 Here's my search so far:

 

 

 

index="test" sourcetype="csv"
| stats count as numColor by color
| eval total=5 
| eval percent=printf("%.2f", (numColor/total)*100)
| sort num(percent)
| table color numColor percent

 

 

 

How do I replace the hardcore variable value "total" with count() function or other methods?
Any help would be appreciated.

Labels (2)
0 Karma
1 Solution

PickleRick
SplunkTrust
SplunkTrust

Sorry, my mistake. sum(numColor), not sum(count). You renamed the column in your stats.

| makeresults 
| eval _raw="red
green
red
blue
green
red
red
green"
| multikv noheader=t
| table Column_1
| rename Column_1 as color| stats count as numColor by color |eventstats sum(numColor) as totalcolors
| eval percentage=numColor/totalcolors
| fields - totalcolors
| fieldformat percentage=round(percentage*100,1)

 

PickleRick_1-1630579139949.png

 

View solution in original post

PickleRick
SplunkTrust
SplunkTrust

There is probably another way. But I'd do your initial search

index="test" sourcetype="csv"
| stats count as numColor by color

Then I'd add eventstats to have sum of the counts in every row

|eventstats sum(count) as totalcolors

So now you can simply evaluate

| eval percentage=numColor/totalcolors
0 Karma

homer07
Explorer

I tried your method, but it doesn't seem to work to use two count function in the same search.

0 Karma

PickleRick
SplunkTrust
SplunkTrust

Sorry, my mistake. sum(numColor), not sum(count). You renamed the column in your stats.

| makeresults 
| eval _raw="red
green
red
blue
green
red
red
green"
| multikv noheader=t
| table Column_1
| rename Column_1 as color| stats count as numColor by color |eventstats sum(numColor) as totalcolors
| eval percentage=numColor/totalcolors
| fields - totalcolors
| fieldformat percentage=round(percentage*100,1)

 

PickleRick_1-1630579139949.png

 

homer07
Explorer

Thanks, it's great!

0 Karma
Get Updates on the Splunk Community!

More Ways To Control Your Costs With Archived Metrics | Register for Tech Talk

Tuesday, May 14, 2024  |  11AM PT / 2PM ET Register to Attend Join us for this Tech Talk and learn how to ...

.conf24 | Personalize your .conf experience with Learning Paths!

Personalize your .conf24 Experience Learning paths allow you to level up your skill sets and dive deeper ...

Threat Hunting Unlocked: How to Uplevel Your Threat Hunting With the PEAK Framework ...

WATCH NOWAs AI starts tackling low level alerts, it's more critical than ever to uplevel your threat hunting ...