Reputation: 456
I currently have TableOne
with one column: ID
. I want to add a derived second column, NumSemesters
which should be the number of occurrences of TableOne_ID
in a second table, TableTwo
.
Essentially, NumSemesters
should be the number of times TableOne.ID
= TableTwo.Student_ID
.
How do I alter my first table to add this second column?
In table one, ID
is the primary key.
Upvotes: 0
Views: 179
Reputation: 330
I think you are looking for something like this.
SELECT TableOne.ID, TableTwo.NumSemesters FROM TableOne INNER JOIN (SELECT ID, COUNT(*) AS NumSemesters FROM TableOne GROUP BY ID) as TableTwo ON TableOne.ID = TableTwo.ID
Jim
Upvotes: 0
Reputation: 7997
Something like this (assuming you already created the column NumSemesters):
update TableOneset NumSemesters = b.idCount
from TableOne a left join
(select Student_ID, count(Student_ID) as 'idCount' from TableTwo groupby Student_ID ) b on a.ID = b.Student_ID
Upvotes: 1