Search code examples
sqlsum

SQL Update if sum of selected columns =5


This should be fairly simple, I've searched but am only finding solutions to much more complex issues.

I have a table (AP9) with a number of columns and I want to set another column to 1 if 5 of the columns are also 1

e.g.:

Pas ColA ColB ColC ColD ColE
0 1 1 1 1 1
0 0 0 1 1 1
0 0 1 1 0 1
0 1 1 1 1 1
0 1 1 1 1 1

What I have tried, and seems to be close is:

UPDATE AP9 
SET Pas = 1 
WHERE (SELECT Pas 
       FROM AP9 
       HAVING SUM(ColA+ColB+ColC+ColD+ColE) = 5);

Thinking that Pas would be st to 1 if the sum of the other columns was 5

But I get an error

Error Code: 1093. You can't specify target table 'AP9' for update in FROM clause

Surely this should be a fairly easy process, but I am pulling my hair out!


Solution

  • Probably the simplest update would be as follows, assuming you only need to update qualifying rows to 1

    update app 
    set pass = 1
    where ColA + colB + colC + colD + colE = 5;
    

    Depending on your RDBMS you could also replace pas with a calculated or computed column to always show the correct 1 or 0 value.