首页 > 解决方案 > 使用 Coalesce 后在 PostgreSQL 9.2 数据库的联接查询中没有返回结果时返回 0

问题描述

我需要帮助在 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 - 如果数据为空(使用 where 子句时),则将数据计数为零, 但在我的情况下它不起作用,因为我不想在 S TABLE 中移动我的 where 条件,因为我将查询稍后使用不同的查询从中获取。可能吗 ?

标签: sqlpostgresqlgroup-by

解决方案


考虑总结WHERE从句的条件:

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

推荐阅读