Click here to Skip to main content
15,900,907 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
HI there, i have a simple question for you all.
I have a table like this one:
ID 1 1 2 3 4 4 5 6
NAME JIM JOHN NICK GEORGE PAUL STEPHEN KELLY JACK
CODE 14 26 26 14 14 26 14 26

I want to create 3 tables from the one above. One that includes only the IDs with code 14 that do not have the same id with code 26. One that includes only the IDs with code 26 that do not have the same id with code 14. And one that includes the IDs with code 14 and code 26. To be more precise i want these tables:

ID 3 5
NAME GEORGE KELLY
CODE 14 14


ID 2 6
NAME NICK JACK
CODE 26 26


ID 1 1 4 4
NAME JIM JOHN PAUL STEPHEN
CODE 14 26 14 26

Thnx in advance for any help guys!
Posted

1 solution

Don't see a reason why you would want to do this, but okay... Create the three tables (for example A, B and C) and select the data into it.

INSERT INTO A (id, name, code) FROM SELECT id, name, code FROM Table1 WHERE Id IN (3, 5)
INSERT INTO B (id, name, code) FROM SELECT id, name, code FROM Table1 WHERE Id IN (2, 6)
etc...



I assume the code can be lost after the data is separated because the new table will add the meaning of that. To be more clear: All records that are moved to table A are implied to have code 14, records in table B 26 and table C have 14 en 26.

To fill the first two tables would be easy but because there are records that have both code 14 and 26 you need to get them out of the way first. To select those you need every record with code 14 and 26, group them by id and then only keep records that has a count of two (because that means it has both code 14 and 26)
The select would become something like this:
SELECT id, name FROM Table1 
  WHERE code in (14, 26)
  GROUP BY id
  HAVING COUNT(id) = 2;


You need to insert those records into table C and after that delete them from Table1 (or whatever the name of the table is). After that you only need to separate the records with either code 14 or 26 from it.

Good luck!
 
Share this answer
 
v2
Comments
jim haras 22-Feb-12 4:49am    
sorry man, maybe i did not explain my problem thoroughly. the table i mentioned above is not my real table but an example. my actual table has over 80000 records. you understand that i cannot do this manually by entering the record id. i want a solution that works automatically for all my records. thnx for your quick response , btw...
E.F. Nijboer 23-Feb-12 3:38am    
I updated my answer and hope it is more helpful with your problem.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900