Postgres width_bucket:函数width_bucket(bigint,integer [])不存在

时间:2020-10-20 09:04:02

标签: postgresql

我运行两个不同的查询。这个很好用

with t(n) as(
    values
           (1),
           (1),
           (1),
           (2),
           (10)
)
select
       width_bucket(n,array[1,3,6,15]) g,
       count(*)
from t
group by g
order by g

但是当我运行此(真实)查询时,它会在存储桶中报告错误

with data as (
    select
           vendor_id,
           count(distinct pi.id) as cnt
    from payment_invoice_items as pii
    join payment_invoices as pi
        on pii.invoice_id = pi.id
        and pii.deleted_at isnull
    group by vendor_id
)
select
       width_bucket(data.cnt, array[1,10,20,30,40,100,200,400]) as grp,
       count(*)
from data
group by grp
order by grp 

data.cnt是一列整数数据。为什么此报告错误?

[42883]错误:函数width_bucket(bigint,integer [])不存在提示:没有函数与给定的名称和参数类型匹配。您可能需要添加显式类型转换。

谢谢

1 个答案:

答案 0 :(得分:1)

COUNT函数返回类型BIGINT,而不是INTEGER。因此,该类型的错误:

[42883]错误:函数width_bucket(bigint,integer [])不存在提示:没有函数与给定的名称和参数类型匹配。您可能需要添加显式类型转换。

您需要将COUNT的结果显式转换为INTEGER才能在函数中使用:

with data as (
    select
           vendor_id,
           count(distinct pi.id) as cnt
    from payment_invoice_items as pii
    join payment_invoices as pi
        on pii.invoice_id = pi.id
        and pii.deleted_at isnull
    group by vendor_id
)
select
       width_bucket(data.cnt::INTEGER, array[1,10,20,30,40,100,200,400]) as grp,
       count(*)
from data
group by grp
order by grp 
相关问题