I’m attempting to update a table using a join statement, but it isn’t exactly working out. I need to be able to update a certain row in the database when one condition is true, using data from a different table. Here is what I have so far, maybe I am close and someone could provide some insight?
UPDATE Project
SET Project.SumAssessments = SUM (Assessment.Amount)
FROM Project
JOIN Assessment ON Project.SumAssessments = SUM (Assessment.Amount)
WHERE Assessment.ProjectCode = @ProjectID
AND Project.ProjectID = @ProjectID
First, I would get rid of the column entirely. It violates one of the most basic rules of proper database design. Don’t duplicate data in your database, because it will pretty much always end up out of sync and even when it doesn’t it will require extra maintenance and care. There are VERY rare cases where this should be violated. Your situation is almost certainly not one of those cases, even if you think it is. With proper indexing there should be no need for that column.
Second, there’s no need to join on the Assessment table based on the
SUM. You’re already joining based on the project code, you just didn’t put that condition in yourONclause where it belongs. Even better, you could just use a subquery to avoid the need for aGROUP BY. Since you’re using what I assume is the Primary Key (ProjectId) the subquery should perform fine.