How to include null values in `tablefunc` query in postgresql?

二次信任 提交于 2019-12-05 17:15:29
Erwin Brandstetter

Use the crosstab() variant with two parameters:

SELECT * FROM crosstab(
   'SELECT zone_id, group_id, area
    FROM   ct
    ORDER  BY 1,2'

   ,'SELECT g FROM generate_series(1,8) g'  -- ! Provide values explicitly
   )
AS ct(
     row_name integer
   , g_1 float8, g_2 float8
   , g_3 float8, g_4 float8
   , g_5 float8, g_6 float8
   , g_7 float8, g_8 float8);

Thereby declaring explicitly which value goes in which output column. So the function knows where to fill in NULL values. In this case generate_series() comes in handy to provide 8 rows with the numbers 1-8. A VALUES expression would be an alternative:

'VALUES (1), (2), (3), (4), (5), (6), (7), (8)'

Also, don't forget the ORDER BY clause in the first parameter query.

I provided a detailed explanation in this related answer.

I can't make it work in the Demo as I can't create the tablefunc extension but it works in my desktop running 9.2.1:

SELECT *
FROM crosstab(' 
    select 
        s.zone_id, s.group_id, area
    from 
        ct
        right join (
            (select distinct zone_id from ct) z(zone_id)
            cross join
            generate_series(1, 8) g(group_id)
        ) s on s.group_id = ct.group_id and s.zone_id = ct.zone_id
    order by s.zone_id, s.group_id
') AS ct (
    row_name integer, 
    g_1 double precision, 
    g_2 double precision, 
    g_3 double precision, 
    g_4 double precision, 
    g_5 double precision, 
    g_6 double precision, 
    g_7 double precision, 
    g_8 double precision
);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!