Rails / SQL语句减去空值

时间:2014-10-16 17:49:29

标签: jquery mysql sql ruby-on-rails

嘿所有我在rails应用程序中使用此查询。我正在尝试查找唯一员工的数量,因此我创建了一个查询,该查询将查找有多少total_employees,然后找出有duplicatesduplicates的{​​{1}}使用id_number计算出来。然后我从duplicates中减去total_employees,给出了唯一个体的数量。 id_number字段不是强制性的,因此id_number为空的duplicates不应包含在计数中。

问题是当我尝试运行查询时unique_employees为空, SELECT SUM(total_count.count) - SUM(duplicate_count.count) as unique_employees, SUM(total_count.count), SUM(duplicate_count.count) FROM ( SELECT COUNT(1) as count FROM participants JOIN training_programs ON training_programs.id = participants.training_program_id WHERE training_programs.category IN ('B', 'C', 'D') AND training_programs.skills_development_id = 123 AND participants.foreign = FALSE AND participants.race = 'African' AND participants.gender = 'Male' AND participants.employed = true ) as total_count, (SELECT SUM(count) as count FROM (SELECT COUNT(id_number)-1 AS count FROM participants JOIN training_programs ON training_programs.id = participants.training_program_id WHERE training_programs.category IN ('B', 'C', 'D') AND training_programs.skills_development_id = 123 AND participants.foreign = FALSE AND participants.race = 'African' AND participants.gender = 'Male' AND participants.employed = true AND participants.id_number <> '' GROUP BY id_number HAVING COUNT(id_number) > 1) as duplicated_records ) as duplicate_count 的数量也将变为空。

这是我的查询

{{1}}

所以我得到了这个

query_results

我的SQL foo不是世界上最好的,所以我试图弄清楚如何将所有空值看作0.我也希望在单个查询中有这个,因为它在循环中运行根据给出的输入,每次保存必须重新运行几十次。

或者上述任何帮助都会很棒。提前致谢

修改

如果我要添加重复项,则查询运行正常。所以查询很好,如果没有重复项,那么无论total_empolyees的数量是多少,查询都会返回0。

1 个答案:

答案 0 :(得分:1)

IFNULL

中包含所有可能产生空值的值
SUM(IFNULL(duplicate_count.count,0))