SQL Server Inserting a previous value into the new column -


i have these 2 tables:

table1: customername billdate

city - beautification lm            2013-05-30 00:00:00.000 city - beautification lm            2013-06-28 00:00:00.000 city - parks/rt 66                  2012-07-12 00:00:00.000 city - parks/rt 66                  2012-07-12 00:00:00.000 

and on...

table2 has field: cyclestartdate

i want insert data table1 table2 following: each unique customername, cyclestartdate billdate previous record. if previous record not exist, replace null 2013-07-1 00:00:00.000.

is possible can that?

if have sql server less 2012, try this

select t.customername, isnull(tp.billdate, '20130701') cyclestartdate table1 t    outer apply (        select top 1 t2.billdate        table1 t2        t2.customername = t.customername , t2.billdate < t.billdate        order t2.billdate desc    ) tp 

if have sql server 2012, see lag() function


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -