如何在Splunk中计算字段和gropuby字段的比例?

问题描述 投票:0回答:1

我有这个表。

Fruits  Result
--------------
Apple   sold
Apple   sold
Apple   instock
Apple   expired
Banana  sold
Banana  sold
Banana  sold
Orange  instock
Orange  instock

我必须在Splunk中生成如下的报告。我想按水果类型来计算,并计算结果的比例。

Fruits  count  instock_ratio expired_ratio sold_ratio
----------------------------------------------------
Apple   4       0.25         0.25          0.5
Banana  3       0            0             1.0
Orange  2       1.0          0             0

在SQL中,我可以得到这个结果。

WITH src AS(
    SELECT
       Fruits,
       count(CASE WHEN result="sold" THEN Fruits ELSE null END) AS sold_count,
       count(CASE WHEN result="instock" THEN Fruits ELSE null END) AS instock_count,
       count(CASE WHEN result="expired" THEN Fruits ELSE null END) AS expired_count,
       count(Fruits) AS total_counts
    FROM table
    GROUP BY Fruits
)
SELECT
   Fruits,
   total_counts,
   sold_count/total_counts,
   instock_count/total_counts,
   expired_count/total_counts
FROM src

谁能帮我用splunk命令?

splunk
1个回答
0
投票

添加以下内容到你的搜索中

| stats count, count(eval(Result="sold")) AS sold_count, count(eval(Result="expired")) AS expired_count, count(eval(Result="instock")) AS instock_count by Fruits
| eval sold_ratio=sold_count/count, expired_ratio=expired_count/count, instock_ratio=instock_count/count | fields - *_count

我们只需计算每个水果的总计数和每个结果的计数即可。要计算出比例,只需将每个计数除以总数即可。

下面是一个例子,说明它的工作原理。它也使用了 foreach 命令,让事情变得更干净。

| makeresults count=100 | eval r1=random()%3 | eval Fruits=case(r1=1, "Apple", r1=2, "Banana", true(), "Orange") | eval r2=random()%3 | eval Result=case(r2=1,"instock", r2=2, "sold", true(), "expired") 
| stats count, count(eval(Result="sold")) AS sold_count, count(eval(Result="expired")) AS expired_count, count(eval(Result="instock")) AS instock_count by Fruits
| foreach *_count [ eval <<MATCHSTR>>_ratio=<<FIELD>>/count ] | fields - *_count
© www.soinside.com 2019 - 2024. All rights reserved.