Home  >  Q&A  >  body text

Display calculation results in SQL with 2 decimal places

I wrote a simple query to find the percentage of two columns, but I want the results to be in a column with only two decimal places. This is what I wrote but I'm getting an error and I can't seem to fix it.

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粉055726146182 days ago357

reply all(1)I'll reply

  • P粉653045807

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

    You cannot use column aliases in the same query. you can do it.

    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

    Or use subquery

    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

    reply
    0
  • Cancelreply