Skip to content
Advertisement

query to insert records to another table by calculating the percentage on a column

I have 2 Postgres tables with the following structure:

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

I have a script below that inserts the data from public.tmp to public.mo table based on the criteria that

  • if the column STATUS has mix values (COMPLIANT and NC) for a particular HOSTNAME then compliant_status is PARTIAL and
  • if all values are COMPLIANT for a particular HOSTNAME then compliant_status is COMPLIANT and
  • if all values are NC for a particular HOSTNAME then compliant_status is NON_COMPLIANT

Now I want to display compliant_status based on the following conditions:

  1. If the no. of COMPLIANT values in STATUS column for a particular HOSTNAME is greater than 80% then the compliant_status is COMPLIANT.
  2. If the no. of COMPLIANT values in STATUS column for a particular HOSTNAME is less than 80% then the compliant_status is NON_COMPLIANT.

Iam expecting the final output as below based on the above data:

HOSTNAME: RhelTest, COMPLIANT %: 88.88%, compliant_status: COMPLIANT

HOSTNAME: Demo1 , COMPLIANT %: 0%, compliant_status: NON_COMPLIANT

HOSTNAME: Demo2 , COMPLIANT %: 100%, compliant_status: COMPLIANT

HOSTNAME: Demo3 , COMPLIANT %: 16.67%, compliant_status: NON_COMPLIANT

Final expected table:

Advertisement

Answer

If I follow you correctly, you can use window functions:

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