在SQLite中计算百分比

时间:2011-10-05 13:26:26

标签: sql sqlite

以下是查询:

select
(
SELECT     COUNT(*)
FROM         Sending s
WHERE     (ConfID = 1) AND (Status = 1)
)
/
(
 (
 SELECT     COUNT(*)
 FROM         Numbers
 WHERE     (ConfID = 1)
 )
 /
 100
)

我想计算百分比。例如,如果查询

SELECT     COUNT(*)
     FROM         Numbers
     WHERE     (ConfID = 1)

给出100而另一个

 SELECT     COUNT(*)
    FROM         Sending s
    WHERE     (ConfID = 1) AND (Status = 1)

结果50结果查询应该返回50,这意味着50%。但是第一个查询结果是2,第二个返回10000,结果查询返回0.我想我应该定义以某种方式返回浮点数等。

谢谢!

2 个答案:

答案 0 :(得分:8)

尝试除100.0而不是100。这将强制转换为浮点数据类型:

select
(
SELECT     COUNT(*)
FROM         Sending s
WHERE     (ConfID = 1) AND (Status = 1)
)
/
(
 (
 SELECT     COUNT(*)
 FROM         Numbers
 WHERE     (ConfID = 1)
 )
 /
 100.0
)

答案 1 :(得分:0)

尝试:

SELECT SUM(CASE status WHEN 1 THEN 100 ELSE 0 END) / COUNT(*)
  FROM numbers
 WHERE confid = 1