sql - Dynamic way of counting number of previous rows in a table that satisfy some condition, over certain columns in the table -


as specific example have table t columns customer , date indicating days on individual customers have made purchases:

customer |   date    ----------------------          | 01/01/2013         | 02/01/2013        | 07/01/2013        | 11/01/2013        b | 03/01/2013        b | 08/01/2013        

i want add column each pair (customer, date) pair (c, d), gives number of pairs (c', d') in t such c = c' , 0 <= days(d) - days(d') <= 7. below table column:

customer |   date     | new_column ----------------------------------          | 01/01/2013 |          1        | 02/01/2013 |          2        | 07/01/2013 |          3         | 11/01/2013 |          2        b | 03/01/2013 |          1        b | 10/01/2013 |          1 

as rough idea of steps used solve problem:

  • create table t' possible pairs (c,d);
  • left join t onto t';
  • create new column: count(date) on (partition customer order date asc rows between 6 preceding , 0 following);
  • omit rows new table t.date null

however, don't think scalable.

cheers help.

let's start ddl. (you'll more answers , better answers if include ddl , sample insert statements in questions.)

create table test (   customer char(1) not null,   purchase_date date not null,   primary key (customer, purchase_date) );  insert test values ('a', '2013-01-01'), ('a', '2013-01-02'), ('a', '2013-01-07'), ('a', '2013-01-11'), ('b', '2013-01-03'), ('b', '2013-01-10'); 

in standard sql, can use along these lines. doesn't require creating table, outer joins, or window functions. it's not clear whether have reason wanting create new table, it's not necessary right data. (i renamed "date" column avoid reserved word.)

select t1.customer, t1.purchase_date, count(*) new_column test t1 inner join test t2 on t1.customer = t2.customer , t2.purchase_date <= t1.purchase_date , t2.purchase_date > t1.purchase_date - interval '7 day' group t1.customer, t1.purchase_date order t1.customer, t1.purchase_date;  customer  purchase_date  new_column --         2013-01-01     1         2013-01-02     2         2013-01-07     3         2013-01-11     2 b         2013-01-03     1 b         2013-01-10     1 

whether scales depends on how db2 handles non-equi joins. db2 explain guide you. i'd expect index on "purchase_date" , restrictive clause perform well.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -