0

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
1
  • unnest() together with array_agg() looks quite suspicious in the SELECT list Commented Dec 1, 2018 at 12:00

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.