Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
380 views
in Technique[技术] by (71.8m points)

divide one row record into 2 rows in sql server

In my Sql table, I want to divide a row record into 2 rows. sample data set given below.

enter image description here

Need to divide 2 rows like this.

enter image description here

This is the query I used

SELECT FRCS2.[CID],FRCS2.[DATE],FRCS2.[Status], 
                    FRCS1.[ID],FRCS1.[DATE],FRCS1.[Status]
FROM #temp FRCS1
INNER JOIN #temp FRCS2
ON FRCS1.[ID] = FRCS2.[ID]

Please help me to solve this. Thanks.

question from:https://stackoverflow.com/questions/65626105/divide-one-row-record-into-2-rows-in-sql-server

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In SQL Server, I would recommend apply:

select v.*
from t cross apply
     (values (id1, date1, status1), (id2, date2, status2)
     ) v(id, date, status);

Note that column names cannot be duplicated in a table. So, this assumes that the columns actually have different names.

This approach is preferred over union all because it only scans the table once. For a small table, the performance difference is negligible. It is noticeable for larger tables and can be quite significant if the "table" is really a subquery, CTE, or view.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...