sql server - How would you write a T-SQL query that supported event study analysis -


i trying create table support simple event study analysis, i'm not sure how best approach this.

i'd create table following columns: customer, date, time on website, outcome. i'm testing premise outcome particular customer on give day if function of time spent on website on current day preceding 5 site visits. i'm envisioning table similar this:

[1]: http://i.stack.imgur.com/yz98l.png

i'm hoping write t-sql query produce output this:

enter image description here

given objective, here questions:

  • assuming indeed possible, how should structure table accomplish objective? there need column refers prior visit? need add index particular column?

  • would considered recursive query?

  • given appropriate table structure, query like?

  • is possible structure query variable determines number of prior periods include in addition current period (for example, if want compare 5 periods 3 periods)?

not sure understand analytic value of matrix

declare @table table (id int,visitdate date,visittime int,outcome varchar(25)) insert @table (id,visitdate,visittime,outcome) values (123,'2015-12-01',100,'p'), (123,'2016-01-01',101,'p'), (123,'2016-02-01',102,'n'), (123,'2016-03-01',100,'p'), (123,'2016-04-01', 99,'n'), (123,'2016-04-09', 98,'p'), (123,'2016-05-09', 99,'p'), (123,'2016-05-14',100,'n'), (123,'2016-06-13', 99,'p'), (123,'2016-06-15', 98,'p')  select *       ,t0 = visittime       ,t1 = lead(visittime,1,0) over(partition id order id,visitdate desc)       ,t2 = lead(visittime,2,0) over(partition id order id,visitdate desc)       ,t3 = lead(visittime,3,0) over(partition id order id,visitdate desc)       ,t4 = lead(visittime,4,0) over(partition id order id,visitdate desc)       ,t5 = lead(visittime,5,0) over(partition id order id,visitdate desc)  @table   order id,visitdate desc 

returns

id  visitdate   visittime   outcome t0  t1  t2  t3  t4  t5 123 2016-06-15  98          p       98  99  100 99  98  99 123 2016-06-13  99          p       99  100 99  98  99  100 123 2016-05-14  100         n       100 99  98  99  100 102 123 2016-05-09  99          p       99  98  99  100 102 101 123 2016-04-09  98          p       98  99  100 102 101 100 123 2016-04-01  99          n       99  100 102 101 100 0 123 2016-03-01  100         p       100 102 101 100 0   0 123 2016-02-01  102         n       102 101 100 0   0   0 123 2016-01-01  101         p       101 100 0   0   0   0 123 2015-12-01  100         p       100 0   0   0   0   0 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -