我正在尝试进行简单的百分比计算,但是无论我做什么,我对字段0
总是以accuracy
结尾。我也尝试过将其强制转换为DOUBLE
,但是没有运气。两个输入都分别生成一个数字,因此我无法弄清楚为什么我总是得到0。我只想在给定的月份内执行(# of TRUE
/ Records
)。我怀疑这里的问题是我按月将其分组,但不知道如何解决。
我是否需要使计数成为该部门的子查询,还是可以在一个查询中全部完成?
+------------+-------+----+
| Date | reg | id |
+------------+-------+----+
| 2020-05-01 | TRUE | 1 |
+------------+-------+----+
| 2020-05-02 | TRUE | 2 |
+------------+-------+----+
| 2020-05-03 | FALSE | 3 |
+------------+-------+----+
| 2020-05-03 | TRUE | 4 |
+------------+-------+----+
| 2020-05-03 | TRUE | 5 |
+------------+-------+----+
| 2020-05-04 | FALSE | 6 |
+------------+-------+----+
SELECT
SUBSTR(date, 1, 7) as month_year,
SUM(CASE WHEN reg = FALSE THEN 1 ELSE 0 END) as error,
SUM(CASE WHEN reg = TRUE THEN 1 ELSE 0 END) as valid,
COUNT(reg) as records,
ROUND(SUM(CASE WHEN reg = TRUE THEN 1 ELSE 0 END)/COUNT(reg), 2) as accuracy
FROM table
GROUP BY 1
ORDER BY 1 DESC
LIMIT 13
答案 0 :(得分:1)
大概是整数除法。但是,无论如何,您不需要划分。替换:
ROUND(SUM(CASE WHEN reg = TRUE THEN 1 ELSE 0 END)/COUNT(reg), 2) as accuracy
使用:
ROUND(AVG(CASE WHEN reg = TRUE THEN 1.0 ELSE 0 END), 2) as accuracy
= TRUE
是多余的,但是我保留了它,因为您将其包含在代码中。