Skip to content
Advertisement

How to divide with each other the two queries with different conditions?

There is a table in which the managers column and the status column. How to calculate the total status of Fully, the divided total of records with all statuses except N / A for each manager?

I tried to portray in this way, but nothing came of it

First Query

SELECT "Manager Name", count("Performance Score") as Perfomance FROM public.hr_dataset  WHERE 
("Performance Score" = 'Fully Meets') GROUP BY "Manager Name"
ORDER BY Perfomance DESC;

Second Query

SELECT "Manager Name", count("Performance Score") FROM public.hr_dataset 
WHERE ("Performance Score" != 'N/A- too early to review') GROUP BY "Manager Name";

Need to recieve two columns with name and values (1 query/2 query)

Advertisement

Answer

You can do conditional aggregation:

SELECT 
    "Manager Name", 
    COUNT(*) FILTER(WHERE "Performance Score" = 'Fully Meets') Perfomance_Fully_Meets,
    COUNT(*) Performance_Not_NA,
    AVG( ("Performance Score" = 'Fully Meets')::int) Performance_Ratio
FROM public.hr_dataset  
WHERE "Performance Score" != 'N/A- too early to review' 
GROUP BY "Manager Name"
ORDER BY Perfomance DESC;

This works as follows:

  • filter on statuses other than 'N/A' (this actually includes the 'Fully Meets' status)
  • aggregate by manager name
  • for each manager, do a conditional count of how many records have status 'Fully Meets', rendered in column Perfomance_Fully_Meets
  • for each manager, count the total of records ('N/A' were filtered out already), in column Performance_Not_NA
  • if you want the ratio of 'Fully Meets' records, you can do it using AVG() on the result of condition Performance Score" = 'Perfomance_Fully_Meets‘; in numeric context, a true condition evaluates as 1 and false as 0.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement