[英]Insert a new row for every change in value in a column
I have a sql table, in which for every change in a value in a certain column say Column C, I want to insert a new row under it to create a new transaction. 我有一个sql表,其中对于某列(例如Column C)中的值的每个更改,我想在其下插入新行以创建新事务。 I am not sure how to find that value change and insert a new row.
我不确定如何找到该值更改并插入新行。 I have been doing this through VB code on the csv file I Import into the table but unable to write it in SQL.
我一直通过导入到表中的csv文件中的VB代码执行此操作,但是无法用SQL编写它。
Sub InsertRows()
Dim r As Long, mcol As String, i As Long
' find last used cell in Column A
r = Cells(Rows.Count, "A").End(xlUp).Row
' get value of last used cell in column A
mcol = Cells(r, 1).Value
' insert rows by looping from bottom
For i = r To 2 Step -1
If Cells(i, 1).Value <> mcol Then
mcol = Cells(i, 1).Value
Rows(i + 1).Insert
End If
Next i
End Sub
Here's the sample data 这是示例数据
ID JOB FNAME LNAME ADDRESS1 ADDRESS2 DATE Concatenated
1234 A John Smith 4378 Anna St Seattle-WA-98040 12/24/2013 1234-A-41632
1234 A John Doe 3564 Lucie Ave Mercer Island-WA-98040 12/24/2013 1234-A-41632
1235 A Alex Smith 4554 Devon Ave Chicago-IL-60563 12/24/2013 1235-A-41632
1235 A Eli Manning 5555 Stranz Lane Dallas-TX-75213 12/24/2013 1235-A-41632
1233 B John Smith 4378 Anna St Seattle-WA-98040 12/24/2013 1233-B-41632
1233 C John Doe 3564 Lucie Ave Mercer Island-WA-98040 12/24/2013 1233-C-41632
1236 D Alex Smith 4554 Devon Ave Chicago-IL-60563 12/24/2013 1236-D-41632
1236 E Eli Manning 5555 Stranz Lane Dallas-TX-75213 12/24/2013 1236-E-41632
Below is the desired output 以下是所需的输出
ID JOB FNAME LNAME ADDRESS1 ADDRESS2 DATE Concatenated
1234 A John Smith 4378 Anna St Seattle-WA-98040 12/24/2013 1234-A-41632
1234 A John Doe 3564 Lucie Ave Mercer Island-WA-98040 12/24/2013 1234-A-41632
1235 A Alex Smith 4554 Devon Ave Chicago-IL-60563 12/24/2013 1235-A-41632
1235 A Eli Manning 5555 Stranz Lane Dallas-TX-75213 12/24/2013 1235-A-41632
1233 B John Smith 4378 Anna St Seattle-WA-98040 12/24/2013 1233-B-41632
1237 C John Doe 3564 Lucie Ave Mercer Island-WA-98040 12/24/2013 1237-C-41632
1236 D Alex Smith 4554 Devon Ave Chicago-IL-60563 12/24/2013 1236-D-41632
1236 E Eli Manning 5555 Stranz Lane Dallas-TX-75213 12/24/2013 1236-E-41632
The column "concatenated" is where i'm trying to find a change and insert a row after every change. 我尝试在其中找到更改并在每次更改后插入一行的“已连接”列。 Any help would be appreciated.
任何帮助,将不胜感激。
you really want to write a stored procedure run either from you data source into you database or time depended in your database. 您确实想编写一个从数据源运行到数据库或时间取决于数据库的存储过程。
here is the code 这是代码
BEGIN; 开始;
ALTER TABLE Test_table ADD COLUMN b1(10,2); ALTER TABLE Test_table添加列b1(10,2);
UPDATE test_table SET romney_pct = CAST (romney AS DECIMAL (10,2)) / CAST (uspres_total AS DECIMAL (10,2); 更新test_table SET romney_pct = CAST(romney AS DECIMAL(10,2))/ CAST(uspres_total AS DECIMAL(10,2);
COMMIT; 承诺;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.