I want to update job date if any records is an earlier date. Trying to use CTE to achieve this:
CREATE TABLE job (jobid int4, jobdate date); INSERT INTO job (jobid, jobdate) VALUES (1, '2016-02-01'), (2, '2016-02-01'), (3, '2016-02-01'), (4, '2016-02-01') ; CREATE TABLE rec (recid int4, recjob int4, recdate date); INSERT INTO rec (recid, recjob, recdate) VALUES (1,1,'2016-02-01'), (2,2,'2016-01-01'), (3,3,'2016-02-01'), (4,4,'2016-02-01') ;
Job number 2 have a record dated earlier than the job date. So I want to update this job with the record date.
WITH cte AS (SELECT jobid,least(min(recdate),jobdate) FROM job LEFT JOIN rec ON recjob=jobid GROUP BY jobid,jobdate HAVING least(min(recdate),jobdate)<jobdate)
Selecting the cte shows correct that job 2 should be updated
SELECT * FROM cte
But updating gives an error: missing FROM-clause entry for table "cte"
UPDATE job SET jobdate=cte.date WHERE jobid IN (SELECT jobid FROM cte)
SQLFiddle: http://sqlfiddle.com/#!15/e9ae6/8
I have never used cte with update, so I need some help to understand this.
TIA,
Specifies a temporary named result set, known as a common table expression (CTE). This is derived from a simple query and defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE or MERGE statement. This clause can also be used in a CREATE VIEW statement as part of its defining SELECT statement.
In PostgreSQL, the CTE(Common Table Expression) is used as a temporary result set that the user can reference within another SQL statement like SELECT, INSERT, UPDATE or DELETE. CTEs are temporary in the sense that they only exist during the execution of the query.
You can use data-modifying statements (INSERT, UPDATE, or DELETE) in WITH.
Try your UPDATE
with the following syntax;
UPDATE job SET jobdate = cte.date FROM cte WHERE job.jobid = cte.jobid
The syntax is as follows:
WITH cte AS ( SELECT * FROM ... ) UPDATE table_to_update SET column_from_table_to_update = cte.some_column FROM cte WHERE table_to_update.id = cte.id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With