Click here to Skip to main content
15,893,564 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Am relatively new to this SQL coding, a little help can be useful.
Question:
How do i save consolidated data in third table from tabel1 and table2.

For example:
Table1 contains following column and data.
ID | Name | Target
11 | Abcd | 123
12 | xyzx | 135

Table2 contains following columns and data.
ID | Candidate | Roll_Number
11 | asdeff    | 12345
11 | dfrsf     | 12346
11 | dfesf     | 12347
12 | erfgv     | 12348
12 | dsfdv     | 12349
12 | dasfr     | 12350
12 | dsadsa    | 12351

Table3 should store data from table1 & table2 after applying functions.
Name | Number of Candidate | Target
Abcd | 3                   | 123
xyzx | 4                   | 135

Note: In the third table the "Number of candidate" column should be COUNTED from table2, respectively.

I need a SQL statements which generates above data in table3.

Thanks
Saiekrishna


What I have tried:

I have used JOIN, DISTINCT, COUNT but couldn't get correct data.
Posted
Updated 22-Feb-16 3:09am
v2

1 solution

This sounds to be a pretty much straight solution
Something like following should do your job-
SQL
--INSERT INTO Table3
SELECT Table1.Name, COUNT(Table2.ID),Table1.Target
FROM Table2
INNER JOIN Table1 ON Table2.ID=Table1.ID
GROUP BY Table1.Name,Table1.Target


Note: Uncomment the INSERT statement once you are sure about the accuracy of the result from the SELECT statement, to insert the result in to Table3.

Hope, it helps :)
 
Share this answer
 
v2
Comments
CHill60 22-Feb-16 6:40am    
You might want to uncomment the line that inserts the data into the table ;)
Suvendu Shekhar Giri 22-Feb-16 9:23am    
True. Just kept that commented so that user can see what is going to be inserted.
I always do that to avoid wrong transaction.
But, yes, I should have mentioned that in a note atleast.
Thanks for your suggestion. Will keep that in mind for future answers.
CHill60 22-Feb-16 11:36am    
I spotted it because I do exactly the same thing :)
Suvendu Shekhar Giri 23-Feb-16 4:17am    
:D great to know that. Thanks :)
Member 10376341 22-Feb-16 7:25am    
@Suvendu Shekhar Giri
Thank you for the reply, i have done exactly the way you described but getting an error.
Following is the error:

Msg 208, Level 16, State 1, Line 1
Invalid object name 'Table2'.

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