开发者

SQL: How to calculate the percentage using SUMS()

开发者 https://www.devze.com 2023-04-02 07:25 出处:网络
I\'m trying to calculate percentages using SUM() to gather totals. CONVERT(decimal(10,2), SUM(cola)/(SUM(cola)+SUM(colb)))

I'm trying to calculate percentages using SUM() to gather totals.

CONVERT(decimal(10,2), SUM(cola)/(SUM(cola)+SUM(colb)))

I've checked and SUM(cola) = 3 and SUM(colb) = 2; So I was expecting it to calculate like...

3/5 = .6; So I was hoping to get returned, 0.60,

Here's the full query:

    SELECT CASE WHEN this < 0 THEN '-'
                ELSE '+' END AS 'Col1',
             开发者_高级运维   SUM(cola) as 'this', SUM(colb) as 'that',
                CONVERT(decimal(10,2), SUM(cola)/(SUM(cola)+SUM(colb)) as 'PCT'
     FROM Table1
    WHERE colc = 'Condition'
 GROUP BY CASE WHEN this < 0 THEN '-'
               ELSE '+' END


You are doing Integer division.

You need at least one operand to be a float type if you want a float result.


Thanks @Oded, (forgot to convert integers to decimal) So, this is what I changed...

SELECT CASE WHEN this < 0 THEN '-' 
                ELSE '+' END AS 'Col1', 
                SUM(cola) as 'this', SUM(colb) as 'that', 
                CONVERT(decimal(10,2), SUM(cola)/(CONVERT(decimal(10,2),
                SUM(cola))+CONVERT(decimal(10,2), SUM(colb))) as 'PCT' 
     FROM Table1 
    WHERE colc = 'Condition' 
 GROUP BY CASE WHEN this < 0 THEN '-' 
               ELSE '+' END 
0

精彩评论

暂无评论...
验证码 换一张
取 消