use [test1_AlplaPROD2.0_Read]

SELECT
	JSON_VALUE(content, '$.EntityId') as labelId,
	a.id
	,ActorName
	--,FORMAT(l.PrintDate, 'yyyy-MM-dd HH:mm') as printDate
	,Format(COALESCE(l.PrintDate, e.ProductionDate), 'yyyy-MM-dd HH:mm') as printDate
	,FORMAT(CreatedDateTime, 'yyyy-MM-dd HH:mm') createdDateTime
    ,COALESCE(l.ArticleHumanReadableId,e.ArticleHumanReadableId) as av
	,COALESCE(l.ArticleDescription, av.Name) as alias
	,COALESCE(l.PrintedCopies, 0) as PrintedCopies
	,COALESCE(p.name,'External Label not tracked') as printerName
	,COALESCE(l.RunningNumber, e.RunningNumber) as runningNumber
	--,*
FROM [support].[AuditLog] (nolock) as a

left join
	[labelling].[InternalLabel] (nolock)  as l on 
	l.id = JSON_VALUE(content, '$.EntityId')

OUTER APPLY (
    SELECT TOP 1 *
    FROM labelling.ExternalLabel e
    WHERE e.id = JSON_VALUE(a.content, '$.EntityId')
    ORDER BY e.Id DESC
) e

left join
	[masterData].[printer] (nolock) as p on
	p.id = l.PrinterId

left join
	[masterData].[article] (nolock) as av on
	av.HumanReadableId = e.ArticleHumanReadableId
where message like '%reprint%'
	and CreatedDateTime > DATEADD(minute, -[intervalCheck], SYSDATETIMEOFFSET())
	and a.id > [ignoreList]
order by CreatedDateTime desc