我正在尝试使用2个查询进行简单的%计算((COMPLETED / TOTAL)* 100),但只有一个结果选择,但结果显示不正确,显示100或0。
查询#1:
select COUNT(CODE) from TABLE1 where ORG = '111' and STATUS in ('A','COM') AND LEFT(DESC, 4) = 'JOBS'
查询#2:
select COUNT(CODE) from TABLE1 where ORG = '111' and STATUS IN ('R', 'A', 'COM') AND LEFT(DESC, 4) = 'JOBS'
我可以做到这一点:
select ((select COUNT(CODE) from TABLE1 where ORG = '111' and STATUS in ('A','COM') AND LEFT(DESC, 4) = 'JOBS')/( select COUNT(CODE) from TABLE1 ORG = '111' and STATUS IN ('R', 'A', 'COM') AND LEFT(DESC, 4) = 'JOBS') *100)
没有成功。正如我所说,它显示0或100。
查询#1结果为202,查询#2结果为228,所以这不是数学问题......
我做错了什么?
答案 0 :(得分:0)
有一件事你可能没注意到。 COUNT(*)返回一个BIGINT
,它就像你在小学那样进行简单的划分。您将 0整数和202/228作为粒子,但未显示。
如果你除了228/208,你会得到1
为了解决这个问题,你必须将你的数字转换为十进制:
SELECT CONVERT(DECIMAL, (
SELECT COUNT(CODE)
FROM TABLE1
WHERE ORG = '111'
AND STATUS IN ('A', 'COM')
AND LEFT([DESC], 4) = 'JOBS'
)) / CONVERT(DECIMAL, (
SELECT COUNT(CODE)
FROM TABLE1 ORG = '111'
AND STATUS IN ('R', 'A', 'COM')
AND LEFT([DESC], 4) = 'JOBS'
) * 100)
答案 1 :(得分:0)
SELECT a.CountCode / b.CountCode
FROM (
select COUNT(CODE) CountCode from TABLE1 where ORG = '111' and STATUS in ('A','COM') AND LEFT(EVT_DESC, 4) = 'JOBS' ) a
, (select COUNT(CODE) CountCode from TABLE1 where ORG = '111' and STATUS IN ('R', 'A', 'COM') AND LEFT(DESC, 4) = 'JOBS' ) b
另外如果你想用十进制做CAST(a.CountCode为十进制(18,3))