SELECT * FROM (SELECT 
	a.id                                                                     AS "id",
	a.protocol                                                               AS "protocol",
	coalesce(a.compatibility_override, a.compatibility)                      AS "compliance",
	a.active                                                                 AS "active",
	a.baseurl                                                                AS "baseUrl",
	ds.eosc_datasource_type                                                  AS "type",
	a.last_aggregation_date                                                  AS "aggrDate",
	coalesce(a.last_aggregation_total, 0)                                    AS "aggrTotal",
	coalesce(a.last_aggregation_mdid, '')                                    AS "aggrMdId",
	a.last_collection_date                                                   AS "collDate",
	coalesce(a.last_collection_total, 0)                                     AS "collTotal",
	coalesce(a.last_collection_mdid, '')                                     AS "collMdId",
	ds.id                                                                    AS "dsId",
	ds.officialname                                                          AS "name",
	ds.englishname                                                           AS "alternativeName",
	ds.namespaceprefix                                                       AS "prefix",
	ds.websiteurl                                                            AS "websiteUrl",
	coalesce((array_agg(o.country))[1], '-')                                 AS "country",
    (array_agg(o.legalname))[1]                                              AS "organization",
    ds.consenttermsofuse                                                     AS "consenttermsofuse",
    ds.fulltextdownload                                                      AS "fulltextdownload",
    ds.primary_provide_gateway                                               AS primary_provide_gateway,
	array_to_string(ds.affiliated_provide_gateways, ',')                     AS affiliated_provide_gateways
FROM dsm_api a
	LEFT OUTER JOIN dsm_services ds ON (a.service = ds.id)
	LEFT OUTER JOIN dsm_service_organization dsorg ON (ds.id = dsorg.service)
	LEFT OUTER JOIN dsm_organizations o ON (dsorg.organization = o.id)
WHERE ds.dedup_main_service = true
GROUP BY
	a.id,
	a.protocol,
	a.compatibility_override,
	a.compatibility,
	a.active,
	a.last_aggregation_date,
	a.last_download_date,
	a.last_collection_date,
	a.last_aggregation_total,
	a.last_download_total,
	a.last_collection_total,
	a.last_aggregation_mdid,
	a.last_download_objid,
	a.last_collection_mdid,
	ds.id,
	ds.officialname,
	ds.englishname,
	ds.namespaceprefix,
	ds.websiteurl,
	ds.consenttermsofuse,
    ds.fulltextdownload,
    ds.primary_provide_gateway,
    ds.affiliated_provide_gateways,
    eosc_datasource_type
) AS t WHERE
