【问题标题】:How to get total and percentage of values more than 10 in SQL Server如何在 SQL Server 中获取大于 10 的值的总数和百分比
【发布时间】:2020-06-25 00:57:55
【问题描述】:

我已经编写了一个 SQL 语句,它产生天数并计算每个天数。

我想要完成的是 10 天以上和以下的计数和百分比。

以下示例数据以及我希望在彩色文本中实现的目标。

非常感谢您的帮助。

【问题讨论】:

    标签: sql-server database tsql


    【解决方案1】:

    如果你只想要最后两天,你可以使用:

    select (case when days_take <= 10 then '10 or less' else 'greater than 10' end) as grp,
           count(*) * 100.0 / sum(count(*)) over () as percentage,
           count(*) as ratio
    from t
    group by (case when days_take <= 10 then '10 or less' else 'greater than 10' end);
    

    【讨论】:

    • 非常感谢@gordon-linoff - 非常感谢
    • 现在我的问题是获取百分比,因此将其向上舍入以使其 = 10 天的总和为 100%。我得到这个结果:66.666666666666 和 33.333333333333,这几乎是 99.99%?
    • @Interalianz 。 . .在这种情况下,这些值实际上应该更像 66.6666667 和 33.3333333。但这一点很好理解。由于四舍五入,这些值加起来可能不等于 100。有一个修复方法,但这可能意味着其中一个值的舍入方式与其他值不同。
    • 我很想看到解决方法。请分享。谢谢大家
    • 嗨@Gordon Linoff,这是我调整它以适应我需要的方法: Round(count() * 100 / sum(count()) over (),0 ) 作为百分比再次感谢您的帮助。
    【解决方案2】:

    在 TSQL 中,可以使用cross apply 和聚合:

    你可以做条件聚合:

    select 
        x.descr,
        1.0 * sum(x.how_many) / sum(sum(x.how_many)) over() as how_many_ratio,
        sum(x.how_many) as how_many_value
    from mytable t
    cross apply (values 
        (
            'greater than 10 days'
            case when days_taken > 10 then how_many else 0 end
        ),
        (
            'less than and 10 days'
            case when days_taken <= 10 then how_many else 0 end
        )
    ) as x(descr, how_many)
    group by x.descr
    

    如果您满足于将所有结果放在一行中,则条件聚合更简单:

    select
        1.0 * sum(case when days_taken > 10 then how_many else 0 end)
            / sum(how_many) as how_many_above_10_ratio,
        sum(case when days_taken > 10 then how_many else 0 end) as how_many_above_10,
        1.0 * sum(case when days_taken <= 10 then how_many else 0 end)
            / sum(how_many) as how_many_below_10_ratio,
        sum(case when days_taken <= 10 then how_many else 0 end) as how_many_below_10
    from mytable
    

    【讨论】:

    • 感谢您的意见@GMB,非常感谢。我仍然是 SQL 的新手 :-( 您的 cmets 我已将它们归档以备将来参考。再次感谢 :-)
    猜你喜欢
    • 1970-01-01
    • 2018-04-05
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 1970-01-01
    相关资源
    最近更新 更多