Author |
Topic |
drunkhammer
Starting Member
5 Posts |
Posted - 2010-08-26 : 12:25:12
|
I'm having difficulty creating a query to combine records. I have a table which contains 1 to 2 records for a specific individual. If an individual has 2 records the records will have different values in 2 fields. I'm attempting to combine these records and insert the data in to a new table. The new table has 4 fields to encapsulate the values of the 2 sets of 2 fields. Below is a basic example of the tablesInitial tableFields: Id, PersonId, T_Code, T_NameSample data: 1, 1234, 45, Milesio2, 1234, 55, Aegyptiam3, 3334, 72, LatiaNew tableFields: Id, PersonId, T_Code_1, T_Name_1, T_Code_2, T_Name_2Resulting data after insert:1, 1234, 45, Milesio, 55, Aegyptiam2, 3334, 72, Latia, NULL, NULLAny assistance is appreciated. |
|
Lamprey
Master Smack Fu Yak Hacker
4614 Posts |
Posted - 2010-08-26 : 14:42:14
|
Here is a query that'll get you the results you want. If you need help with inserting into a new table let us know.-- Set up Sample DataDECLARE @Table TABLE (Id INT, PersonId INT, T_Code INT, T_Name VARCHAR(50))INSERT @TableSELECT 1, 1234, 45, 'Milesio'UNION ALL SELECT 2, 1234, 55, 'Aegyptiam'UNION ALL SELECT 3, 3334, 72, 'Latia'-- Create CTE;WITH MyTableAS(SELECT *, ROW_NUMBER() OVER (PARTITION BY PersonID ORDER BY ID) AS RowNumFROM @Table)-- Return ResultsSELECT --A.ID, A.PersonId, A.T_Code AS T_Code_1, A.T_Code AS T_Name_1, B.T_Code AS T_Code_2, B.T_Code AS T_Name_2FROM MyTable AS ALEFT OUTER JOIN MyTable AS B ON A.PersonID = B.PersonID AND A.RowNum <> B.RowNumWHERE A.RowNum = 1 AND ( B.RowNum = 2 OR B.RowNum IS NULL )ORDER BY A.PersonID |
 |
|
jimf
Master Smack Fu Yak Hacker
2875 Posts |
Posted - 2010-08-26 : 15:32:12
|
deleted due to stupidity Jim |
 |
|
drunkhammer
Starting Member
5 Posts |
Posted - 2010-08-26 : 18:28:58
|
Thank you Lamprey! This resolved my issue. |
 |
|
|
|
|