Move one row value to another in SQL

☆樱花仙子☆ 提交于 2019-12-31 06:48:05

问题


I currently have a temporary table like so

DBName API50 CounterValue
NULL    NULL   1
test1   34.5   NULL
NULL    NULL   2
test1   38.5   NULL

I want a script which will make my temporary table as below

DBName API50 CounterValue
test1   34.5   1
test1   38.5   2

回答1:


If your table has a primary key, and you always want to associate the CounterValue field with the next field in the table, you can do a self-join:

SELECT t1.DBName, t1.API50, t2.CounterValue
FROM MyTable t1 INNER JOIN MyTable t2 ON t1.PrimaryKey -1 = t2.PrimaryKey
WHERE t1.DBName IS NOT NULL



回答2:


I like AHiggins answer as it solves the problem in SQL as it is probably expected. But what initially stuck me when I read your question is: Why solve it in SQL at all? It seems like the data is not originally created inside the database but somehow imported. If I am correct - or if exporting the table, editing and re-importing - is an option then you could solve this with a regular expression. All notable text editors can do this for you (I tested this with NotePad++).

If the table is in a text file using a tabulator \t as delimiter you could simply replace all

NULL\tNULL\t(.*)\n(.*)\t(.*)\tNULL

with \2\t\3\t\1.



来源:https://stackoverflow.com/questions/22226543/move-one-row-value-to-another-in-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!