即使没有行匹配查询,如何使用合并,分组和联接来强制postgres返回0

时间:2019-02-26 11:13:26

标签: sql postgresql join coalesce

我一直在无奈地尝试获取以下SQL语句以返回查询结果,如果没有与查询匹配的行,则默认为0。

这是预期的结果:

  vol  | year 
-------+------
   0   | 2018

相反,我得到了:

 vol | year 
-----+------
(0 rows)

这是sql语句:

select coalesce(vol,0) as vol, year
from (select sum(vol) as vol, year
      from schema.fact_data
         join schema.period_data
            on schema.fact_data.period_tag = schema.period_data.tag 
         join schema.product_data
            on schema.fact_data.product_tag = 
schema.product_data.tag
         join schema.market_data
            on schema.fact_data.market_tag = schema.market_data.tag
      where "retailer"='MadeUpRetailer'
        and "product_tag"='FakeProductTag'
        and "year"='2018' group by year
     ) as DerivedTable;

我知道查询有效,因为它在有数据时返回数据。只是没有默认设置为0 ...

对于找到这种情况的任何帮助,将不胜感激!

3 个答案:

答案 0 :(得分:2)

使用子查询DerivedTable,您可以编写:

SELECT coalesce(DerivedTable.vol, 0) AS vol,
       y.year
FROM (VALUES ('2018'::text)) AS y(year)
   LEFT JOIN (SELECT ...) AS DerivedTable
      ON DerivedTable.year = y.year;

答案 1 :(得分:1)

删除GROUP BY(和外部查询):

select 2018 as year, coalesce(sum(vol), 0) as vol
from schema.fact_data f join
     schema.period_data p
     on f.period_tag = p.tag join
     schema.product_data pr
     on f.product_tag = pr.tag join
     schema.market_data m
     on fd.market_tag = m.tag
where "retailer" = 'MadeUpRetailer' and
      "product_tag" = 'FakeProductTag' and
      "year" = '2018';

没有GROUP BY的聚合查询总是返回恰好一行,因此这应该做您想要的。

编辑:

查询看起来像这样:

select v.yyyy as year, coalesce(sum(vol), 0) as vol
from (values (2018), (2019)) v(yyyy) left join
     schema.fact_data f
     on f.year = v.yyyy left join  -- this is just an example.  I have no idea where year is coming from
     schema.period_data p
     on f.period_tag = p.tag left join
     schema.product_data pr
     on f.product_tag = pr.tag left join
     schema.market_data m
     on fd.market_tag = m.tag
group by v.yyyy

但是,您必须将where条件移动到适当的on子句。我不知道这些列从哪里来。

答案 2 :(得分:0)

根据您发布的代码,您不清楚在哪个表中有year列。
如果该表中没有2018年的行,则可以使用UNION仅获取1行,如下所示:

select sum(vol) as vol, year
from schema.fact_data innrt join schema.period_data
on schema.fact_data.period_tag = schema.period_data.tag 
inner join schema.product_data
on schema.fact_data.product_tag = schema.product_data.tag
inner join schema.market_data
on schema.fact_data.market_tag = schema.market_data.tag
where 
  "retailer"='MadeUpRetailer' and 
  "product_tag"='FakeProductTag' and 
  "year"='2018'
group by "year"
union 
select 0 as vol, '2018' as year
where not exists (
  select 1 from tablename where "year" = '2018' 
)

如果2018年有行,那么第二个查询将不会获取任何内容,