搜尋

首頁  >  問答  >  主體

以2位小數顯示SQL中的計算結果

我寫了一個簡單的查詢來找出兩列的百分比,但我希望結果在只有兩位小數的列中。這是我寫的,但我遇到了錯誤,而且我似乎無法修復它。

SELECT 
    Small_Bags,
    Total_Bags,
    (Small_Bags / Total_Bags) * 100 AS Small_Bags_Percent
    (Select CAST (Small_Bags_Percent AS DECIMAL (10,2)))
FROM Table_Bags
WHERE Total_Bags <>0

P粉055726146P粉055726146231 天前421

全部回覆(1)我來回復

  • P粉653045807

    P粉6530458072024-04-03 12:46:35

    您不能在同一查詢中使用列別名。你可以做到這一點。

    select Small_Bags
        , Total_Bags
        , (Small_Bags / Total_Bags) * 100 AS Small_Bags_Percent
        , cast(((Small_Bags / Total_Bags) * 100) as decimal(10,2))
    from Table_Bags
    where Total_Bags > 0

    或使用子查詢

    select t1.Small_Bags, t1.Total_Bags, t1.Small_Bags_Percent
        , cast(t1.Small_Bags_Percent as decimal(10,2))
    from 
        (select Small_Bags
            , Total_Bags
            , (Small_Bags / Total_Bags) * 100 AS Small_Bags_Percent
            , cast(((Small_Bags / Total_Bags) * 100) as decimal(10,2))
        from Table_Bags
        where Total_Bags > 0) t1

    回覆
    0
  • 取消回覆