SELECT 
	s.id                                                                    AS "id",
	s.officialname                                                          AS "officialName",
	s.englishname                                                           AS "englishName",
	s._typology_to_remove_                                                  AS "typology",
	s.eosc_type                                                             AS "eoscType",
	s.eosc_datasource_type                                                  AS "eoscDatasourceType", 
	s.registeredby                                                          AS "registeredBy", 
	s.registrationdate::text                                                AS "registrationDate", 
	MIN(a.first_collection_date)	                                        AS "firstCollectionDate",
	MAX(a.last_collection_date)                                             AS "lastCollectionDate", 
	(array_remove(array_agg(a.last_collection_total order by a.last_collection_date desc), NULL))[1] AS "lastCollectionTotal",
	array_remove(array_agg(DISTINCT coalesce(a.compatibility_override, a.compatibility)), NULL)      AS "compatibilities",
	array_remove(array_agg(DISTINCT o.id||' @@@ '||o.legalname), NULL)                               AS "organizations"
FROM 
	dsm_services s
	left outer join dsm_api a on (s.id = a.service) 
	left outer join dsm_service_organization dso on (s.id = dso.service) 
	left outer join dsm_organizations o on (o.id = dso.organization) 
WHERE 
	s.registrationdate is not null 
	and s.registeredby is not null
	and s.managed = true
GROUP BY 
	s.id,
	s.officialname,
	s.englishname,
	s._typology_to_remove_,
	s.eosc_type,
	s.eosc_datasource_type, 
	s.registeredby, 
	s.registrationdate
HAVING
	s.registrationdate < max(a.last_collection_date)
	and sum(a.last_collection_total) > 0
ORDER BY s.registrationdate desc 
LIMIT ?

