I've got a table with many columns some of these are:
product_id, territory_id, quarter_num (it's a number of a quarter from 1 to 28 for instance).
There are some other columns but they aren't necessary in this query.
I need to count number of distinct products in every territory in every cumulative quarter: only 1 first, 1+2 second, 1+2+3 third and so on until from 1 till 28.
Before this query was realized in QlikSence with a loop. Now I need to rewrite it in PostgreSQL in one query (even in one CTE part of a long query) using standard SQL with no loops etc.
It would be simply something like this:
select *
,count(distinct product_id)
filter(where some_condition)
over(partition by territory_id order by quarter_num)
as cum_filtered_product_count
from some_table
If I had no distinct which not realized in window functions. I've broken my head, read and tried to use many advices here but still have found no correct solution. Any help will be appreciated.
PS The solution with two subquieris where the first one counts distinctly in a single quarter in a group and the second one sums the results of the first one in a window function cumulatively doesn't work. Because the latter subquery potentially sums the same products.
DISTINCTfiltering?array_agg() as arras a window function in a subquery/CTE, then(select count(distinct e) from unnest(arr)e)on that.select count(distinct arv) from (select unnest(art.arr) from (select array_agg(val) over () as arr from test.array) art) arv;It works ok but I'm confused that if I miss distinct it returns the numbers of rows squared. Do I do anything wrong?