简体   繁体   中英

sql update with previous month data

Have a database which we have one column data wrong in such a way: its current month record is actually next months data. eg

recordA     2014-12-01  3.5
recordB     2014-12-01  1.5
recordC     2014-12-01  5.5
recordD     2014-12-01  3.5


recordB     2014-11-01  3.8
recordC     2014-11-01  6.7
recordD     2014-11-01  1.1

recordA     2014-10-01  8.5
recordB     2014-10-01  3.5
recordC     2014-10-01  4.4
recordD     2014-10-01  1.5

...

so basically, currently 2014-12-01 data are actually 2015-01-01 data, 2014-11-01 data are actually 2014-12-01 data, how can i update these record with previous month record? also there maybe some missing months for one particular record. Eg recordA 2014-11-01 is missing, in this case either create a new 2014-11-01 record with 2014-10-11 record, or just dont update.

This is a quite complex sql to me, pls help.

Use the DateAdd function with a where condition on recordA.

Update Table_Name_Here set DateField_Name_Here = DateAdd(month, 1, DateField_Name_Here) Where RecordTypeField_Name_Here = 'recordA';

If the table has other columns which have data mapped to the right dates, then try the following steps :

  1. Get the recordA records into a temporary table, say #CorrectHelpTable. Make sure you draw the primary key from the source table as well, as we will use this to map to the new values.

  2. Make the updates as mentioned above by me in that temporary table.

  3. Update the source table comparing for dates that exist and connecting by the primary key as well, update the third column (that says 3.5 etc) with values from #CorrectHelpTable.

  4. For dates that don't exist on the source table, insert as many records. You may have to decide what values you are going to give for the other columns in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM