【问题标题】:Postgresql count divided by countPostgresql 计数除以计数
【发布时间】:2020-06-29 18:16:30
【问题描述】:

如果迈阿密,我正在尝试按月在该市获得销售成功率。我拥有的变量是:呼叫 ID、呼叫日期、城市和呼叫状态(销售或不销售)。我在成功率列中有 0,是语法错误还是数据类型错误?代码使用 PostgreSQL 编写。

select date_trunc('month', call_date)::DATE as date,
       count(c.id) FILTER (WHERE c.status='sale') as success_cnt,
       count(c.id) as all_cnt,
       sum((count(c.id) FILTER (WHERE c.status='sale)'))/count(c.id)) over() as success_rate
       from user.call as c
where city='Miami')
group by 1;

【问题讨论】:

    标签: sql postgresql date count sum


    【解决方案1】:

    我有点困惑窗口函数的来源。对于成功率,您可以使用:

    select date_trunc('month', call_date)::date as date,
           count(*) FILTER (where c.status = 'sale') as success_cnt,
           count(*) as all_cnt,
           avg( (c.status = 'sale')::int ) as success_rate
    from user.call c
    where city = 'Miami'
    group by 1;
    

    【讨论】:

    • 您好,您能解释一下为什么要对字符串应用平均函数,或者在这种情况下如何将字符串转换为整数?
    • 字符串与一个值进行比较,产生一个布尔值。然后将该布尔值转换为整数(1 = true,0 = false)。取这些整数的平均值会产生成功率。
    • 我在平均函数中添加了一个条件,现在它显示 ERROR: syntax error at or near "filter" 这是我添加的 avg((c.status = 'sale' filter ( where profession in ('student', 'unemployed')))::int)
    • 试试avg( (c.status = 'sale')::int ) FILTER (WHERE profession IN ('student', 'unemployed'))
    【解决方案2】:

    count() 返回一个整数,当你将整数相除时,你得到一个整数结果,余数被丢弃。如果您想要小数结果,则需要在除法之前将其中一个输入转换为小数类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2018-01-12
      • 2011-08-07
      • 1970-01-01
      • 2018-12-08
      • 2021-09-09
      • 2011-12-28
      相关资源
      最近更新 更多