Search code examples
sqlpostgresqlsql-updatepostgresql-9.3

Update with results of another sql


With the sql below I count how many records I have in tableB for each code. The total field is assigned the result of the count and the code the code field of the record.

SELECT
    "count" (*) as total,
    tableB."code" as code
FROM
    tableB 
WHERE
    tableB.code LIKE '%1'
GROUP BY
    tableB.code

In tableA I have a sequence field and I update with the result of total (obtained in the previous sql) plus 1 Do this for each code. I tried this and it did not work, can someone help me?

UPDATE tableA
SET tableA.sequence = (tableB.total + 1) where tableA."code" = tableB.code
FROM
    (
        SELECT
            "count" (*) as total,
            tableB."code" as code
        FROM
            tableB 
        WHERE
            tableB.code LIKE '%1'
        GROUP BY
            tableB.code
    )

I edited for my tables are as mostar believe facillita understanding of my need

tableA

code  sequence
100      null
200      null


table B

code  sequence
100      1
100      2
100      3
100      4
......
100      17
200      1
200      2
200      3
200      4
......
200      23

Need to update the sequence blank field in tableA with the number 18 to code = 100
Need to update the sequence blank field in tableA with the number 24 to code = 200


Solution

  • This assumes that code is unique in table_a:

    with max_seq as (
       select code,
              max(sequence) + 1 as max_seq
       from table_b
       group by code
    ) 
    update table_a
      set sequence = ms.max_seq
    from max_seq ms
    where table_a.code = ms.code;
    

    SQLFiddle example: http://sqlfiddle.com/#!15/745a7/1