【问题标题】:NRQL percentage of one subset over another一个子集相对于另一个子集的 NRQL 百分比
【发布时间】:2020-08-17 19:00:40
【问题描述】:

我有一个很大的事件表,里面有很多不同类型的事件,我正在制作一个 New Relic 图表来显示一种事件与另一种事件的百分比。 (不是表格中总行数的百分比)。

所以在这个例子中是分段表:

id  name
1   foo      
2   bar
3   baz
4   bar

我会通过这样的查询获取 foo 事件:

select count(*) from Segment where name='foo'

我的问题:如何获得 foo 事件与 bar 事件的百分比?我一直在尝试加入两个查询,将每个“保存为”一个特定的名称,但还没有运气。有谁知道我们是否/如何制作通用表表达式以用于查询/图表?

【问题讨论】:

    标签: sql newrelic nrql


    【解决方案1】:

    您可以使用条件聚合:

    select (sum(case when name = 'foo' then 1.0 else 0 end) /
            sum(case when name = 'bar' then 1.0 else 0 end)
           ) as foo_bar_ratio
    from segment;
    

    编辑:

    也许这将在 NRLQ 中起作用:

    select filter(count(*), where name = 'foo') / filter (count(*), where name = 'bar') as foo_bar_ratio
    from segment;
    

    【讨论】:

    • 谢谢!这听起来我们正在接近(!),但这给出了“意外的'何时'”NRQL语法错误 - 如此接近但到目前为止......
    【解决方案2】:

    要使用 ctes,你需要引用它两次。一个为绿色值,一个为红色值。例如(第一个是加载数据):

    
    with mock as (select * from (values (1, 'red'), (2, 'green'), (3, 'blue'), (4, 'green')) as mock(id, color)),
         aggregated as (
             select count(*), color
             from mock
             group by color
         )
    
    select ag1.count::float / ag2.count::float, ag1.color
    from aggregated ag1,
         aggregated ag2
    where ag2.color = 'green'
    

    我在这里使用 postgres

    【讨论】:

    • 谢谢!我还没有听说过 CTE,而这正是我需要的东西。看看那里的语法,我敢打赌这对于各种数据库/设置会略有不同,所以我可能错误地将它作为一个 SQL 问题,并将编辑为 NRQL
    【解决方案3】:

    您可以使用 PIVOT,这应该可以在 oracle 和 mssql 中使用,但不确定 NRQL。

    DEMO

    select (FOO_COUNTER/BAR_COUNTER) * 100 from  (
    select * from table1
    pivot(count(id) as counter for name in ('foo' foo, 'bar' bar))) x;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-20
      • 2018-12-17
      • 1970-01-01
      相关资源
      最近更新 更多