2

I have this statement that works, but it's unbridled, as in it SUMs up the whole column, I want introduce date range but I'm getting an error.

HERE IS WHAT IS WORKING

UPDATE payroll_employee e
    SET hours = l.total
FROM (SELECT employee, SUM(end_date - start_date) AS total
    FROM payroll_timelog
    GROUP BY employee) l
WHERE e.id = l.employee

I want to introduce a date filter. Then I tried this CTE,

WITH cte AS (
  SELECT employee_id, end_date SUM(end_date - start_date) AS total
    FROM payroll_timelog
    WHERE employee_id = 1, AND end_date > 2020-09-01
)
UPDATE payroll_employee e
   SET hours = total
FROM cte
WHERE e.id = 1;

Tried casting date to 2020-09-01::date, 2020-09-01::timestamp etc, still won't work. any help will be appreciated.

2
  • What does it mean "won't work"? Add input parameters and expected result. Commented Oct 9, 2020 at 0:23
  • You have a comma before the AND so the query won't parse. Commented Oct 9, 2020 at 0:50

1 Answer 1

2

I think you just have syntax errors:

WITH cte AS (
      SELECT employee_id, SUM(end_date - start_date) AS total
      FROM payroll_timelog
      WHERE employee_id = 1 AND end_date > '2020-09-01'
      GROUP BY employee_id
)
UPDATE payroll_employee e
   SET hours = cte.total
FROM cte
WHERE e.id = 1;
Sign up to request clarification or add additional context in comments.

1 Comment

Got : syntax error at or near "(" LINE 2: SELECT employee_id, end_date SUM(end_date - start_date...

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.