Use a CASE
statement to check if RecordNumber = 0 | 2147483647
.
Try this version:
select Content->>'Group' as "Group",
min(case when Content->>'RecordNumber' = '0'
then Content->>'When'
else null
end ) "Start",
max(case when Content->>'RecordNumber' = '2147483647'
then Content->>'When'
else null
end ) "Stop",
count(*) as "Count"
from DocumentStore
group by Content->>'Group'
order by Content->>'Group'
;
The result:
| Group | Start | Stop | Count |
|-------|------------|------------|-------|
| 0 | 1490280300 | 1490280500 | 3 |
| 1 | 1490280600 | 1490280700 | 2 |
| 2 | 1490280900 | NULL | 2 |
As Evan CarrollEvan Carroll pointed out, you can also take advantage of the FILTER
clause. Have a look at 4.2.7 Aggregate expressions in the Postgres docs.
select Content->>'Group' as "Group",
min(Content->>'When') filter (where Content->>'RecordNumber' = '0') "Start",
max(Content->>'When') filter (where Content->>'RecordNumber' = '2147483647') "Stop",
count(*) as "Count"
from DocumentStore
group by Content->>'Group'
order by Content->>'Group'
;
Check it here: http://rextester.com/ADYG46620