0

How do you insert this query with an update? I've tried all possible combinations and nothing seems to work!

UPDATE Test_table2
SET Pledge_Status = closed
WHERE (
    SELECT SUM(pledgers.Pledge_payment_amt) AS pledged
    FROM Test_table2  AS recipients
    LEFT JOIN Test_table2 AS pledgers
    ON recipients.GIFT_NO = pledgers.PLEDGE_GIFT_NO
    GROUP BY recipients.GIFT_NO
    HAVING recipients.Pledge_Amt >= pledged
    ORDER BY recipients.CRSID ASC
);

Schema (all varchar):

ID, Name, Pledge_Amount , Pledge_payment_amt , Gift_No, Pledge_Gift_No, Pledge_Open/Closed

Thank you so very much!

user42479
  • 17
  • 3
  • Please try to provide the table schema at least, this makes understanding your question a lot easier. And if you want to go the extra mile, take the time to create an example on http://sqlfiddle.com/. – S.B. Apr 11 '14 at 18:53
  • sqlfiddle is awesome. Thanks http://sqlfiddle.com/#!2/aecf2 – user42479 Apr 11 '14 at 19:35

1 Answers1

0

Parallel to this question I suggest that you use WHERE ... IN SELECT. Also, you need to pass the ID of each row from the subselect to the main query, and since you didn't provide a table schema, we can only guess here:

UPDATE Test_table2
SET Pledge_Status = closed
WHERE [your id column] IN (
    SELECT [your id column]
    FROM Test_table2  AS recipients
    LEFT JOIN Test_table2 AS pledgers
    ON recipients.GIFT_NO = pledgers.PLEDGE_GIFT_NO
    GROUP BY recipients.GIFT_NO
    HAVING recipients.Pledge_Amt >= SUM(pledgers.Pledge_payment_amt)
    /*ORDER BY recipients.CRSID ASC <-- no need to order anything here */
);
Community
  • 1
  • 1
S.B.
  • 2,920
  • 1
  • 17
  • 25
  • Thanks. I decided to change play with my query and I wrote this: UPDATE Test_table2 set Pledge_Status = closed where Test_table2.GIFT_NO in ( select GIFT_NO FROM ( SELECT recipients.*,SUM(pledgers.Pledge_payment_amt) AS pledged FROM Test_table2 AS recipients LEFT JOIN Test_table2 AS pledgers ON recipients.GIFT_NO = pledgers.PLEDGE_GIFT_NO GROUP BY recipients.GIFT_NO HAVING recipients.Pledge_Amt >= pledged ) ); Why is this wrong? – user42479 Apr 11 '14 at 20:53
  • `select GIFT_NO FROM (SELECT...` - You can't put a sub-SELECT in place of the table name. Also, the error message you get from the Database should explain most of your problems. – S.B. Apr 11 '14 at 21:04