sql - Group by dynamic time period -


for problem i'll try create simplified example.
table "order":

id |    date    | client | product | product_limit_period (in months) 1  | 2015-01-01 | bob    | table   | 1 2  | 2015-01-31 | bob    | table   | 1 3  | 2015-02-01 | bob    | table   | 1 4  | 2015-01-01 | mary   | lamb    | 12 5  | 2015-06-01 | mary   | lamb    | 12 6  | 2016-01-01 | mary   | lamb    | 12 7  | 2016-12-31 | mary   | lamb    | 12 

this result, i'd get:

client | product | group | count bob    | table   | 1     | 2       #id 1, 2 bob    | table   | 2     | 1       #id 3 mary   | lamb    | 3     | 2       #id 4, 5 mary   | lamb    | 4     | 2       #id 6, 7 

every product has limit , limit period (in months). need able see if there clients have ordered product more limit allows in period. the period in months might 1 month or several years in months. possible period 1 month, 12 months, 24 months, ... until 108 months (9 years).

i feel need use combination of window functions , group by. haven't figured out how.

i'm using postgres 9.1. please let me know if there more information should provide.

any appreciated, pointing me right direction!

edit:
clarify how grouping works: limit period starts first order. bob's first order 2015-01-01 , period ends 2015-01-31. 2015-02-01 starts second period. a period starts first day of month , ends last day of month.

no need complicate both window , group by, add case either window or group, here:

t=# select   client , product , count(1) , string_agg(id::text,',') so44 group   client , product , date_trunc(case when product_limit_period = 1 'month' else 'year' end,date);   client  |  product  | count | string_agg ----------+-----------+-------+------------   bob     |  table    |     2 | 1,2   bob     |  table    |     1 | 3   mary    |  lamb     |     2 | 4,5   mary    |  lamb     |     2 | 6,7 (4 rows) 

sample:

t=# create table so44 (i int,"date" date,client text,product text,product_limit_period int); create table t=# copy so44 stdin delimiter '|'; enter data copied followed newline. end backslash , period on line itself. >> 1  | 2015-01-01 | bob    | table   | 1 >> 2  | 2015-01-31 | bob    | table   | 1 3  | 2015-02-01 | bob    | table   | 1 4  | 2015-01-01 | mary   | lamb    | 12 5  | 2015-06-01 | mary   | lamb    | 12 6  | 2016-01-01 | mary   | lamb    | 12 7  | 2016-12-31 | mary   | lamb    | 12>> >> >> >> >> >> \. copy 7 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -