我正在尝试查找在SQL中收到的消息的成功率。因此,我创建一个带有消息ID和操作(已发送或已接收)的表,然后计算否。收到的消息数/总数消息。这是我的代码:
CREATE TABLE msg (id INTEGER, action TEXT);
INSERT INTO msg VALUES (1, 'sent');
INSERT INTO msg VALUES (1, 'received');
INSERT INTO msg VALUES (2, 'sent');
INSERT INTO msg VALUES (2, 'received');
INSERT INTO msg VALUES (3, 'sent');
INSERT INTO msg VALUES (4, 'sent');
INSERT INTO msg VALUES (5, 'sent');
SELECT SUM(CASE WHEN action = 'received' THEN 1 ELSE 0 END)/COUNT( DISTINCT id) AS success_rate FROM msg;
这给我0作为输出。为什么?
答案 0 :(得分:0)
因为您的数据库进行整数除法。简单添加一个小数点:
SELECT SUM(CASE WHEN action = 'received' THEN 1.0 ELSE 0 END) / COUNT(DISTINCT id) AS success_rate
FROM msg;
我可能想除以发送的数字-以防万一:
SELECT (SUM(CASE WHEN action = 'received' THEN 1.0 ELSE 0 END) /
SUM(CASE WHEN action = 'sent' THEN 1.0 END)
) AS success_rate
FROM msg;
或在两种情况下都使用唯一帐户:
SELECT (COUNT(DISTINCT CASE WHEN action = 'received' THEN id END) /
COUNT(DISTINCT id)
) AS success_rate
FROM msg;
如果id
是唯一的(对我来说似乎很合理),则可以简化为:
SELECT AVG(CASE WHEN action = 'received' THEN 1.0 ELSE 0 END) AS success_rate
FROM msg;