两者都选择产生数字。
但是,我似乎无法分开。
期望输出为~9%
代码:
select
(select count(b.booking_id) from booking b where b.pickup_date > '01 feb 2014' and b.pickup_date < '01 mar 2014')
/
(select count(q.quote_id) from quoting q where q.pickup_date > '01 feb 2014' and q.pickup_date < '01 mar 2014')
答案 0 :(得分:1)
select CAST(A.X AS NUMERIC)/ CAST(NULLIF(B.Y, 0) AS NUMERIC)
FROM
(select count(b.booking_id) AS X
from booking b
where b.pickup_date > '01 feb 2014'
and b.pickup_date < '01 mar 2014') A
,
(select count(q.quote_id) AS Y
from quoting q
where q.pickup_date > '01 feb 2014'
and q.pickup_date < '01 mar 2014') B
你总是得到零的原因是
SELECT (50000 /550000)
两个传递的值都是INT,返回值也是INT,没有转换数据类型。
但是,如果你要做如下
SELECT CAST(50000 AS NUMERIC)/ CAST(550000 AS NUMERIC)
或者甚至
SELECT (50000 /550000.12121212)
您将获得正确的结果。原因是在First查询中,您正在显式转换为数据类型Numeric。
在第二个查询中,由于数据类型优先级,Sql Server会从INT到DECIMAL进行隐式转换。阅读此处以了解有关Data Type Precedence (Transact-SQL)
答案 1 :(得分:0)
由于您正在使用整数,因此select正在进行整数运算。 您需要将计数语句转换为双精度才能在2/4的情况发生时获得结果,并检查空值
PSEUDO CODE
SELECT CAST(A AS DECIMAL(13,5) / nullif(CAST (B AS DECIMAL(13,5), 0.0)