简体   繁体   中英

How to skip null values in PostgreSQL query?

I have a query in database table name "c_hw_day" in postgresql

select  pr.c_period_id,
        unnest(array_agg_mult(array[hd.wd1,hd.wd2,hd.wd3,hd.wd4,hd.wd5,hd.wd6,hd.wd7,hd.wd8,hd.wd9,hd.wd10,hd.hd1,hd.hd2,hd.hd2,hd.hd3,hd.hd4,hd.hd5,hd.hd6,hd.hd7,hd.hd8,hd.hd9,hd.hd10])) as wd_hd 
from    c_hw_day hd
  left join c_period pr on (hd.c_period_id = pr.c_period_id) 
group by 1

result like

|   ID    |       Weekend        |
----------+-----------------------
| 1000051 |  2018-11-30 00:00:00 |
| 1000051 |                      |
| 1000051 |                      |
| 1000051 |  2018-12-07 00:00:00 |
| 1000051 |                      |
| 1000051 |                      |
| 1000051 |                      |
| 1000051 |  2018-12-14 00:00:00 |

I want to skip the null value like

|   ID    |       Weekend        |
----------+-----------------------
| 1000051 |  2018-11-30 00:00:00 |
| 1000051 |  2018-12-07 00:00:00 |
| 1000051 |  2018-12-14 00:00:00 |

I would would not do this using arrays. I would just use a lateral join:

select  pr.c_period_id, wd_hd
from c_hw_day hd left join
     c_period pr 
     on hd.c_period_id = pr.c_period_id lateral join
     (values (hd.wd1, hd.wd2, hd.wd3, hd.wd4, hd.wd5, hd.wd6, hd.wd7, hd.wd8, hd.wd9, hd.wd10, hd.hd1, hd.hd2, hd.hd2, hd.hd3, hd.hd4, hd.hd5, hd.hd6, hd.hd7, hd.hd8, hd.hd9, hd.hd10
     ) v(hd)
where hd is not null;

This logic is much clearer. Without the outer group by , I suspect it is faster as well.

the most lasiest way - put your query into subquery if you don't have a lot of data will be ok

select * from (
    select  pr.c_period_id,
           unnest(array_agg_mult(array[hd.wd1,hd.wd2,hd.wd3,hd.wd4,hd.wd5,hd.wd6,hd.wd7,hd.wd8,hd.wd9,hd.wd10,hd.hd1,hd.hd2,hd.hd2,hd.hd3,hd.hd4,hd.hd5,hd.hd6,hd.hd7,hd.hd8,hd.hd9,hd.hd10])) as wd_hd 
    from    c_hw_day hd
      left join c_period pr on (hd.c_period_id = pr.c_period_id) 
    group by 1
)q1
where wd_hd is not null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM