使用Coalesce

时间:2019-03-15 13:38:25

标签: sql postgresql group-by

我需要帮助,已在PostgreSQL 9.2中编写了一个查询,如下所示,我需要 如果没有结果,则返回表示零的行,即使尝试使用COALESCE,当前也不会返回记录。

With S as (select test.Name as Test,result.value as result,concat(person.first_name,' ', person.last_name) as "Name",
extract (Year from (select  (age (patient.birth_date)))) as age
from  clinlims.analysis
INNER JOIN clinlims.test on analysis.test_id=test.id
INNER JOIN clinlims.result on analysis.id = result.analysis_id
INNER JOIN clinlims.sample_item on sample_item.id = analysis.sampitem_id
INNER JOIN clinlims.sample_human on sample_human.samp_id = sample_item.samp_id
INNER JOIN clinlims.patient on patient.id = sample_human.patient_id
INNER JOIN clinlims.person on person.id = patient.person_id)

select  Test , coalesce (count(*),0) as "Number Positive" 
from S where result = 'value' and test = 'Haemoglobin' 
group by Test

我已经在这里PostgreSQL - count data as zero if it is null (when where clause is used) 中检查了解决方案 但由于我不想在S TABLE中移动where条件,因此在我的情况下不起作用,因为稍后我将使用其他查询从该条件中进行查询。 可能吗 ?

1 个答案:

答案 0 :(得分:0)

考虑对WHERE子句的条件求和:

select  Test, 
        sum((result = 'value' and test = 'Haemoglobin')::integer) as "Number Positive" 
from S
group by Test