with cte as (
select
	organisation.Name as OrganisationName,
	site.Name as SiteName,
	spec.Name as SpecificationName,
	fi.Id as FormInstanceId,
	(
	   select max( result.LastUpdated )
	   From (
			select organisation.LastUpdated as LastUpdated
			union all
			select site.LastUpdated as LastUpdated
			union all 
			select spec.LastUpdated as LastUpdated
			union all
			select fi.LastUpdated as LastUpdated) as result
	) as LastUpdated,
	(
		select ffi.DisplayValue
		from Forms.FormFieldInstances as ffi
		join CustomFields.CustomFields as cf
			on cf.Id = ffi.CustomFieldId
			and cf.Guid = '45821C2D-9D6E-4C82-AC57-965755960422' --Domain cf guid
		where ffi.FormInstanceId = fi.Id
		and ffi.Value = @domainGuid
	) as DomainGuid
from Printer.Specifications as spec
join Printer.Sites as site
	on site.Id = spec.SiteId
join printer.Organisations as organisation
	on organisation.Id = site.OrganisationId
join Forms.FormInstances as fi
	on fi.Id = spec.FormInstanceId
	and fi.Deleted = 0
)
select
	cte.OrganisationName,
	cte.SiteName,
	cte.SpecificationName,
	PrintProcess.DisplayValue as PrintProcess,	
	cte.LastUpdated
from cte
cross apply (
		select
			ffi.DisplayValue
		from Forms.FormFieldInstances as ffi
		join CustomFields.CustomFields as cf
			on cf.Id = ffi.CustomFieldId
			and cf.Guid = '1F2AEB33-DA9C-4563-BE88-177F485E789B' --Print Process cf Guid
		where ffi.FormInstanceId = cte.FormInstanceId) as PrintProcess
where DomainGuid is not null
order by
	OrganisationName, SiteName, SpecificationName
