【问题标题】:How to count transaction on the basis of bins and type如何根据 bin 和 type 计算交易
【发布时间】:2021-01-19 13:20:47
【问题描述】:

我在 MySQL DB 中有下表。

我需要构建一份考虑垃圾箱的报告(基于数量和类型)

我尝试过使用以下代码

select TYPE, 
        case when TYPE is null
            then @total := count(*)
            else count(*)
        end as counter
    from mytable
    group by TYPE
    with rollup

但是,我无法获得上述要求格式的报告。

【问题讨论】:

    标签: mysql sql count pivot case


    【解决方案1】:

    您可以在子查询中计算桶,然后在外部查询中进行条件聚合:

    select
        amount_range,
        sum(type = 'A') typeA,
        sum(type = 'B') typeB,
        sum(type = 'C') typeC,
        sum(type = 'D') typeD,
        count(*) all_types
    from (
        select t.*, 
            case 
                when amount > 1100 then '1001-1300'
                when amount >  900 then '901-1100'
                when amount >  700 then '701-900'
                else '500-700'
            end as amount_range
        from mytable
        where amount between 500 and 1300
    ) t
    group by amount_range
    

    实际上,没有真正需要子查询。在 MySQL 中,你可以这样做:

    select
        case 
            when amount > 1100 then '1001-1300'
            when amount >  900 then '901-1100'
            when amount >  700 then '701-900'
            else '500-700'
        end as amount_range,
        sum(type = 'A') typeA,
        sum(type = 'B') typeB,
        sum(type = 'C') typeC,
        sum(type = 'D') typeD,
        count(*) all_types
    from mytable
    where amount between 500 and 1300
    group by amount_range
    

    编辑

    如果您想要记录总数的比率,请使用窗口函数(在 MySQL 8.0 中可用):

    select
        case 
            when amount > 1100 then '1001-1300'
            when amount >  900 then '901-1100'
            when amount >  700 then '701-900'
            else '500-700'
        end as amount_range,
        sum(type = 'A')/sum(count(*)) over() typeA_ratio,
        sum(type = 'B')/sum(count(*)) over() typeB_ratio,
        sum(type = 'C')/sum(count(*)) over() typeC_ratio,
        sum(type = 'D')/sum(count(*)) over() typeD_ratio,
        count(*)/sum(count(*)) over() all_types_ratio
    from mytable
    where amount between 500 and 1300
    group by amount_range
    

    【讨论】:

    • 您好,您的代码有效。但是,我现在的要求是从总记录中获取百分比。你能更新答案吗?
    • @NikhilKumarSingh:在发布答案后编辑问题不是一个好习惯(它会使好的答案无效)。由于这是一个非常简单的更改,因此我编辑了一次答案。
    • over() 在 MySQL 工作台环境之外使用时出现语法错误。
    猜你喜欢
    • 2021-04-22
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-05
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    相关资源
    最近更新 更多