Is it possible to group and the following data in pgsql:
(TL;DR: Note the similar target entries for the two print_names qz.M2 and qz.M1)
| print_name | target |
|---|---|
| qz.R | q3zA |
| qz.S | NULL |
| qz.M1 | q2zA |
| qz.M1 | q1zA |
| qz.M2 | q2zA |
| qz.M2 | q1zA |
in such a way that the distinct values of target are still in the result while the doubling of qz.M* is avoided.
The result desired would therefore be:
| print_name | target |
|---|---|
| qz.R | q3zA |
| qz.S | NULL |
| qz.M1 | q2zA |
| qz.M2 | q1zA |
I tried:
SELECT min(target) FROM Table GROUP BY print_name;
However, this of course only yields one of two entries in target.
Thank you for your help!
CodePudding user response:
Your desired results would seem to indicate just a simple aggregate:
select print_name, Max(target) target
from t
group by print_name
Note your sample data does not include any reliable method or sorting, max() will be based on string ordering.
CodePudding user response:
I dont think this is achievable without casing specific print_name if you want consistent answer.
SELECT t.print_name
FROM Table t
CASE
WHEN t.print_name = 'qz.M1' THEN max(t.target)
WHEN t.print_name = 'qz.M2' THEN min(t.target)
ELSE t.target END as Target
GROUP BY t.print_name
