嘿所有我在rails应用程序中使用此查询。我正在尝试查找唯一员工的数量,因此我创建了一个查询,该查询将查找有多少total_employees
,然后找出有duplicates
个duplicates
的{{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}}
所以我得到了这个
我的SQL foo不是世界上最好的,所以我试图弄清楚如何将所有空值看作0.我也希望在单个查询中有这个,因为它在循环中运行根据给出的输入,每次保存必须重新运行几十次。
或者上述任何帮助都会很棒。提前致谢
修改
如果我要添加重复项,则查询运行正常。所以查询很好,如果没有重复项,那么无论total_empolyees的数量是多少,查询都会返回0。
答案 0 :(得分:1)
在IFNULL
SUM(IFNULL(duplicate_count.count,0))