Skip to content
Advertisement

PSQL query to insert the records from one table to another based on condition

I have 2 Postgres tables with the following structure:

Lets say I have data in the tmp table as below:

Now I want to write a psql INSERT INTO query which will copy the data from public.tmp to public.mo table and also perform below condition

When a Host has mix values in STATUS column, for eg if HOST: RhelTest

  • has 2 values in STATUS column as ‘COMPLIANT’ and ‘NC’ then the column compliant_status should have the value ‘PARTIAL’ for such rows
  • or if there is only one value like ‘COMPLIANT’ then the column compliant_status should have the value ‘COMPLIANT’ for such rows
  • or if there is only one value like ‘NC’ then the column compliant_status should have the value ‘NON_COMPLIANT’ for such rows

Finally Expected output in the public.mo table:

Advertisement

Answer

You can use window functions and a case expression. Here is one way to do it, assuming that there are only two possible values for status, as shown in your data:

The idea is to compare the minimum and maximum values of status for each host. If there are different, then compliant_status is “PARTIAL”. Else, we turn “NC” to “NON_COMPLIANT”, and leave the other value (“COMPLIANT”) as it is.

The subquery is not strictly necessary here, we could very well use the window functions directly in the outer query; I used it because it avoids repeating the same expressions again and again.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement