postgresql add tag
Moshinoki
I'm trying to iterate over the calendar created in this fiddle:

<>https://dbfiddle.uk/?rdbms=postgres_12&fiddle=33d616e417e83fa55a0c23ce227455a6

however, the foreach statement is getting some kind of problem.
Is there a way to make this work???
Top Answer
Truilus
`foreach` is a PL/pgSQL structure. You can not use it in a SQL statement. 

You are probably looking for `unnest()` but if you just want a list of dates or ranges, `generate_series()` is probably much easier


```
select daterange(dt::date, (dt + interval '1 month')::date)
from generate_series(date_trunc('month', current_date - interval '11 month'),
                     date_trunc('month', current_date - interval '1 month'), 
                     interval '1 month') as g(dt)
```

A naive integration into your query might look like this: 

    with calendar (date_range) as (
      select daterange(dt::date, (dt + interval '1 month')::date)
      from generate_series(date_trunc('month', current_date - interval '11 month'),
                           date_trunc('month', current_date - interval '1 month'), 
                           interval '1 month') as g(dt))
    )                       
    select
      unit,
      active_month,
      subscriptions
    from 
    (
        select
          u.name unit,
          x active_month,
          count(s.id) subscriptions
        from
          {{tenant}}.subscriptions_usersubscription s
          left join {{tenant}}.events_unit u on u.id = s.unit_id
        where exists (select * 
                      from calendar c
                      where s.created_at::date <@ c.date_range)
        group by
          s.created_at,
          unit
        order by
          active_month,
          unit
      ) inner_query
    group by
      active_month,
      unit,
      subscriptions
    order by
      active_month,
      unit
    end loop;
    
There might be better ways to integrate the test for the range, e.g. by using a  join against the calendar table, but without more details this is a bit difficult to suggest.

Enter question or answer id or url (and optionally further answer ids/urls from the same question) from

Separate each id/url with a space. No need to list your own answers; they will be imported automatically.