0

I am trying to add up columns where the ID are the same. I'm new to MySQL but it appears that Group By is what I need.

Here is my attempt but it gives me a syntax error

|SiteID|StaffID|Holiday|Total

Update SiteStaff
SET Total = SUM(h.Holiday) 
GROUP BY h.StaffID
3
  • see this post. you cant directly use group by stackoverflow.com/questions/6898935/… Commented Jun 1, 2015 at 9:52
  • what is h.? Thats not coming from anywhere. Commented Jun 1, 2015 at 9:53
  • It had it in an example i looked at. I assumed it was a group name Commented Jun 1, 2015 at 10:23

3 Answers 3

1

I suspect you have a holiday table. If so, you want a query that uses join with update, and looks something like this:

Update SiteStaff ss LEFT JOIN
       (SELECT h.StaffId, SUM(h.holiday) as total
        FROM Holidays h
        GROUP BY h.StaffID
       ) h
       ON ss.StaffId = h.StaffId
    SET ss.Total = COALESCE(t.total, 0);
Sign up to request clarification or add additional context in comments.

Comments

0

I think there may be following reasons of the error:-

  1. You have used h.Holidayin your code. So what is h here ?
  2. Second reason may be you have to use separate code to find the SUM first and the UPDATE the table.

Comments

0

Worked it out from looking at more examples

UPDATE SiteStaff p, (SELECT StaffID, SUM(Holiday) as mysum
 FROM SiteStaff GROUP BY StaffID) as s

    SET p.Total = s.mysum
    WHERE p.StaffID = s.StaffID 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.