Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 query urgent

Author  Topic 

chbala85
Starting Member

49 Posts

Posted - 2013-08-23 : 12:02:54
Hi all,

i have table like below

patients:

paid name cptcd c1 c2 c3 loc
1 aaa cpd9 oc1 oc2 oc3 aa
2 bbb cpd9 oc1 oc3 bb
3 ddd cpd9 oc1 oc3 cc
4 eee cpd9 oc1 oc2 dd

i need insert data into another table like below


paid name cptcd codeinfo loc
1 aaa cpd9 oc1 aa
1 aaa cpd9 oc2 aa
1 aaa cpd9 oc3 aa
2 bbb cpd9 oc1 bb
2 bbb cpd9 oc3 bb
3 ddd cpd9 oc1 cc
3 ddd cpd9 oc3 cc
4 eee cpd9 oc1 dd
4 eee cpd9 oc2 dd


please help me ......................

James K
Master Smack Fu Yak Hacker

3873 Posts

Posted - 2013-08-23 : 13:28:12
Use unpivot:
INSERT INTO YourNewTable (paid, name, cptcd, codeinfo, loc)
SELECT
paid, name, cptcd, codeinf, loc
FROM
Patients
UNPIVOT (codeinfo FOR newLoc IN ([c1],[c2],[c3])) U
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-08-24 : 11:15:19
Also this if its in version before 2005

SELECT
paid, name, cptcd, codeinf, c1 AS loc
FROM
Patients
UNION ALL
SELECT
paid, name, cptcd, codeinf, c2
FROM
Patients
UNION ALL
SELECT
paid, name, cptcd, codeinfo, c3
FROM
Patients


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-08-24 : 11:15:51
quote:
Originally posted by James K

Use unpivot:
INSERT INTO YourNewTable (paid, name, cptcd, codeinfo, loc)
SELECT
paid, name, cptcd, codeinfo, newloc
FROM
Patients
UNPIVOT (codeinfo FOR newLoc IN ([c1],[c2],[c3])) U




------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -