I have a sql Table of the following manner:
Table_Name Field_Name New_Value Create_Date
TableTest Loading Hours 25 12/12/2015 2:56:26 p.m.
TableTest Loading Hours 15 12/12/2015 2:30:23 p.m.
TableTest Loading Hours 11 12/12/2015 2:09:42 p.m.
TableTest Loading_Percentage 35.8 12/12/2015 2:56:26 p.m.
TableTest Loading_Percentage 15.5 12/12/2015 2:30:23 p.m.
What i want to do is to be able to transform the above, How best can I do this efficiently? I could potentially have more values in the loading hours in the table above, and this would need to appear logically as presented in the transformed data below.
TableTest Field_Name OldValue NewValue DateTime
TableTest Loading Hours 15 25 12/12/2015 2:56:26 p.m.
TableTest Loading Hours 11 15 12/12/2015 2:30:23 p.m.
TableTest Loading Hours NULL 11 12/12/2015 2:09:42 p.m.
TableTest Loading_Percentage 15.5 35.8 12/12/2015 2:56:26 p.m.
TableTest Loading_Percentage NULL 15.5 12/12/2015 2:30:23 p.m.
Thanks for the help in advance.
Cheers
Your scenario is exactly what the lag
window function is designed for. Unfortunately, lag
is not available in SQL Server 2008. Until you upgrade, you can do the following:
with cte as (
select *,
row_number() over (partition by table_name, field_name order by create_date) as rn
from tbl
)
select curr.table_name,
curr.field_name,
prev.new_value as old_value,
curr.new_value,
curr.create_date
from cte curr
left join cte prev
on prev.table_name = curr.table_name
and prev.field_name = curr.field_name
on prev.rn = curr.rn + 1
order by curr.table_name, curr.field_name, curr.rn desc
If you ever upgrade to SQL Server 2012+, the query can be written more simply, and get a nice boost in performance, by using lag
:
select table_name,
field_name,
lag(new_value) over (partition by table_name, field_name order by create_date) as old_value,
new_value,
create_date
from tbl
order by table_name, field_name, create_date desc
Handle this scenario in Trigger. Add Insert and Update trigger for the table and use the trigger to achieve the functionality which you required. When ever insert/update the data into the table, the trigger should get the last inserted/updated value based on the Field_Name and insert a new record with New and old value.
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.