[英]SQL: How to calculate the percentage using SUMS()
I'm trying to calculate percentages using SUM() to gather totals. 我正在尝试使用SUM()来计算百分比来收集总数。
CONVERT(decimal(10,2), SUM(cola)/(SUM(cola)+SUM(colb)))
I've checked and SUM(cola) = 3 and SUM(colb) = 2; 我已经检查过SUM(可乐)= 3和SUM(colb)= 2; So I was expecting it to calculate like...
所以我期待它像......一样计算
3/5 = .6; 3/5 = .6; So I was hoping to get returned, 0.60,
所以我希望能回来,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 . 你在做Integer部门 。
You need at least one operand to be a float type if you want a float result. 如果需要float结果,则至少需要一个操作数才能成为float类型。
Thanks @Oded, (forgot to convert integers to decimal) So, this is what I changed... 谢谢@Oded,(忘记将整数转换为十进制)所以,这就是我改变的...
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.