Skip to content
Advertisement

Add Column to Result of Postgres Dynamic Query

I have a table that looks like this:

I rearranged it to this:

Right now, the order of the systems is alphabetical but I created a mapping table in which it orders the priority of the systems

Is there a way to adjust the order such that it reflects the priority and is as such:

Advertisement

Answer

You may find the count of all systems for a specific (Date,Scenario) by using Count(*) over (Partition By Scenario,Date), and the count of only passed systems for that (Date,Scenario) by using Aggregate Filter as the following, count(*) filter (where Result='PASS') over (Partition By Scenario,Date).

Then compare the two counts, if they are equal then set the overall result as PASS.

Consider the following:

See a demo from db<>fiddle.

For the second required output, you may use the following function:

The first parameter in the function qr_selector lets you to choose what query to execute, 1 for the first output, 2 for the second output. The second parameter Scenario_selector lets you to filter the Scenario values, where the default value is ‘all’.

i.e. to select the first output result for all Scenario values use Select pvt(1);, and to select the second output result for Scenario = 'Proj1' use Select pvt(2,'Proj1');

See a demo from db<>fiddle.

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