0
SELECT 
    req,
    SUM(CASE WHEN (stage='Selected') THEN count ELSE NULL END) AS selected,
    SUM(CASE WHEN (stage='Initial Selection') THEN count ELSE NULL END) AS "Initial Selection",
    SUM(CASE WHEN (stage='Hr Round') THEN count ELSE NULL END) AS "Hr Round"
FROM table1
GROUP BY req
;

In the above Postgres query, the value for stage is passed statically (hard-coded) in CASE expression, how can we pass the value for stage dynamically from the result of another query?

Francisco Puga
  • 23,869
  • 5
  • 48
  • 64
  • 2
    You might want to use `SUM(count) FILTER (WHERE stage = …)` instead of `CASE` expressions – Bergi Apr 01 '22 at 09:57
  • Just use a subselect in place of the value you want to be dynamic. – Bergi Apr 01 '22 at 09:57
  • If the number of columns you want returned by your query needs to change depending on the number of rows that some other table has, there is no good way to do that. You will need to construct your query text dynamically then execute it. – jjanes Apr 01 '22 at 17:08
  • Could it be that you are looking for is the pivoting? https://stackoverflow.com/questions/28087948/dynamic-pivot-query-using-postgresql-9-3 – Umut TEKİN Apr 02 '22 at 11:10
  • If you will add `stage` field to `group by`, then query will be returning the data as you wanted. – Ramin Faracov Apr 05 '22 at 22:03

0 Answers0