943,909 Members | Top Members by Rank

Ad:
  • MS SQL Discussion Thread
  • Unsolved
  • Views: 1893
  • MS SQL RSS
Oct 9th, 2008
0

Split record into 2 records

Expand Post »
Hi,
I am trying to break each record into 2 records but failed
Is it possible?
What is the correct way to do it?
Thanks in advance!!!

For Example:
I have a table that contains 100 records . Each record has the following 10 columns:

Col1, Col2, Col3, Col4, Col5, Col6, Col7
A MT 30 UK 0 70 FR
A SM 30 IL 0 0 PS

And that the result that I want to achieve for the 2 records:

ID JoinID Col1, Col2, Col3, Col4
1 1 Col1 MT UK Yes
2 1 Col3 MT FR No
3 2 Col1 SM IL Yes
4 2 Col3 SM PS Yes


ID - An Incremental id
JoinID - A Join ID to join the 2 records
Col1 - Contains the Col1 title for the first line And Col3 title for the second line.
Col2 - Contains the Col2 value for both lines.
Col3 - Contains the Col4 value for the first line And Col7 value for the second line.
Col4 - If Col5 value = 0 Then the value for the first line is 'Yes' Else 'No'
And for the second line, if Col6 value = 0 Then the value 'Yes' Else 'No'
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
lekfir is offline Offline
2 posts
since Oct 2008
Oct 12th, 2008
0

Re: Split record into 2 records

Try this code below:

MS SQL Syntax (Toggle Plain Text)
  1. SELECT 1 AS Col1, 'MT' AS Col2, 30 AS Col3, 'UK' AS Col4, 0 AS Col5, 70 AS Col6, 'FR' AS Col7
  2. INTO #tmpX
  3. union ALL
  4. SELECT 2 AS Col1, 'SM' AS Col2, 30 AS Col3, 'IL' AS Col4, 0 AS Col5, 0 AS Col6, 'PS' AS Col7
  5.  
  6.  
  7. SELECT Identity(int, 1, 1) AS ID, *
  8. INTO #tmpResult
  9. FROM (
  10. SELECT Col1 AS JoinID, 'Col1' AS Col1, Col2, Col4 AS Col3, case when Col5 = 0 then 'Yes' else 'No' end AS Col4
  11. FROM #tmpX
  12. union ALL
  13. SELECT Col1 AS JoinID, 'Col3' AS Col1, Col2, Col4 AS Col3, case when Col6 = 0 then 'Yes' else 'No' end AS Col4
  14. FROM #tmpX
  15. ) X
  16. ORDER BY JoinID
  17.  
  18. SELECT * FROM #tmpResult
  19.  
  20. DROP TABLE #tmpResult
  21. DROP TABLE #tmpX
Reputation Points: 10
Solved Threads: 13
Light Poster
huangzhi is offline Offline
48 posts
since Feb 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in MS SQL Forum Timeline: Codings
Next Thread in MS SQL Forum Timeline: Error converting data type varchar to datetime





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC