为缺少的列值Postgres插入零值行

时间:2016-08-07 22:20:39

标签: sql database postgresql psql

我有这张桌子(elev_table):

 country      | cat |    elev
--------------+-----+----------
 USA          |   0 |    41.46
 USA          |   1 |   878.90
 USA          |   2 |    78.01    
 CAN          |   0 |    46.00
 CAN          |   1 |    78.92
 CAN          |   2 |    78.01
 CAN          |   4 |   667.77
 CAN          |   5 |    10.80

如何创建一个查询来返回同一个表,并填充缺少的cat值? cat列的值必须为(-1到5),但不是每个国家/地区值都包含每个cat值。

基本上,对于我表中的每个国家/地区,我需要每个cat值为-1到5的高程值行.......

例如,我希望结果表看起来像:

 country      | cat |    elev
--------------+-----+----------
 USA          |  -1 |        0
 USA          |   0 |    41.46
 USA          |   1 |   878.90
 USA          |   2 |    78.01
 USA          |   3 |        0
 USA          |   4 |        0
 USA          |   5 |        0  
 CAN          |  -1 |        0 
 CAN          |   0 |    46.00
 CAN          |   1 |    78.92
 CAN          |   2 |    78.01
 CAN          |   3 |        0
 CAN          |   4 |   667.77
 CAN          |   5 |    10.80

我相信0会很好,但也许NULL会更好吗?

我已尝试过以下查询,但这不会为每个国家/地区创建缺少的行值...我知道我遗漏了一些但似乎无法弄清楚是什么!!!

with cat_series as(
  select generate_series(-1,5) as fullcat
)

select fullcat, coalesce(sum(t.elev),0), t.country
from cat_series
  left join elev_table t on cat_series.fullcat=t.cat
group by fullcat, t.country
order by fullcat, t.country;

对于postgres来说还是一个新手,sql。任何帮助或指示将不胜感激!

1 个答案:

答案 0 :(得分:0)

您可以使用cross join后跟left join

select c.country, g.cat, coalesce(sum(t.elev), 0)
from (select distinct country from elev_table) c cross join
     generate_series(-1, 5) as g(cat) left join
     elev_table et
     on et.country = c.country and et.cat = g.cat
group by c.country, g.cat;

我在查询中留下了group by,虽然根据示例数据,这已经足够了:

select c.country, g.cat, coalesce(t.elev, 0)
from (select distinct country from elev_table) c cross join
     generate_series(-1, 5) as g(cat) left join
     elev_table et
     on et.country = c.country and et.cat = g.cat;

如果您希望coalesce()改为NULL,则可以移除0