【问题标题】:displaying decimals in calculated columns在计算列中显示小数
【发布时间】:2018-12-24 11:03:34
【问题描述】:

我有以下有效的代码,但我希望“pcttotalorders”列有 4 个小数位。 enter image description here

select
    vendorno as 'Vendor', count (*) as 'Number Of Orders', count (*)*100/(
                                                                            select
                                                                                count(*)
                                                                            from
                                                                                mas_tfi.dbo.ap_invoicehistoryheader
                                                                                                                    ) as pcttotalorders
from
    mas_tfi.dbo.ap_invoicehistoryheader
group by
    vendorno
order by
    'Number of Orders' desc;

【问题讨论】:

标签: sql select count


【解决方案1】:

这似乎是这个问题的重复: Write a number with two decimal places SQL server 只需更改小数函数的参数,使选择列中的列看起来像--

CONVERT(
        DECIMAL(10,4), 
        (COUNT(*)*100/(SELECT COUNT(*) FROM mas_tfi.dbo.ap_invoicehistoryheader))                                                                                                                   
        ) AS pcttotalorders

【讨论】:

    【解决方案2】:

    试试SQL server格式化函数

    Select
    vendorno as 'Vendor', count (*) as 'Number Of Orders',   
     Format(count (*)*100/(
                                                                            select
                                                                                count(*)
                                                                            from
    
    mas_tfi.dbo.ap_invoicehistoryheader
                                                                                                                    ), 
    "##.####") as pcttotalorders
    from
    mas_tfi.dbo.ap_invoicehistoryheader
    Group by
    vendorno
    order by
    'Number of Orders' desc;
    

    参考 https://docs.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql?view=sql-server-2017

    【讨论】:

    • 这将产生所需的格式,但我认为值得指出的是 format 函数返回一个 nvarchar 而不是一个数值,如果 OP 要这样做,这可能会导致意外行为尝试对这些值进行排序或使用它们进行进一步计算。我认为劳拉使用convert 的方法在大多数情况下可能会更好。
    猜你喜欢
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多