Display calculation results in SQL with 2 decimal places
P粉055726146
P粉055726146 2024-04-02 14:23:34
0
1
364

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粉055726146
P粉055726146

reply all(1)
P粉653045807

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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!