3 tables: Processo
, Evento
, Alerta
The goal is to make a query that returns all processes by adding the columns of the event type and date of the most recent event MAX(DataEvento)
and the next alert (smaller date greater than the current date) / p>
SELECT p.id
,p.scope
,p.entrydate
,p.applicant
,p.status
,MAX(ev.eventdatetime) lastevent
,ev.type
,ev.eventobs
,MIN(al.deadlinedate) nextalert
,al.alertobs
FROM process p
LEFT JOIN event ev
ON ev.processid = p.id
LEFT JOIN alert al
ON al.eventid = ev.eventid
AND al.expiredate > getdate()
GROUP BY p.id
,p.scope
,p.entrydate
,p.applicant
,p.status
,ev.type
,ev.eventobs
,al.expiredate
,al.alertobs
The above code repeats all processes several times, depending on the number of events.
SELECT p.id
,p.scope
,p.entrydate
,p.applicant
,p.status
,MAX(ev.eventdatetime) lastevent
,ev.type
,ev.eventobs
,MIN(al.deadlinedate) nextalert
,al.alertobs
FROM process p
INNER JOIN event ev
ON ev.processid = p.id
INNER JOIN alert al
ON al.eventid = ev.eventid
WHERE ev.processid = p.id
AND a.expiredate > getdate()
GROUP BY p.id
,p.scope
,p.entrydate
,p.applicant
,p.status
,ev.type
,ev.eventobs
,al.alertobs
Lists only one process, the one that has the most recent event.
SELECT DISTINCT p.id
,p.scope
,p.entrydate
,p.applicant
,p.status
,(SELECT TYPE
,MAX(ev.eventdatetime) lastevent
,eventobs
FROM event ev
WHERE ev.processid = p.id
GROUP BY TYPE
,eventobs)
,(SELECT MIN(a.expiredate) nextalert
,alertobs
FROM event ev
INNER JOIN alert a
ON ev.eventid = a.eventid
WHERE ev.processid = p.id
AND a.expire > getdate())
FROM process p
ORDER BY p.id ASC
Here's the error:
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
What I want is to list all the processes each appears once and the query fields are displayed, adding the date, type and observations of the last event and the date and observations of the next alert, eg:
1|Registo|21/06/2018|João Sousa|Activo|21/06/2018|Entrada do processo|Observações do evento|26/06/2018|Prazo para resposta
2|Pedido|21/06/2018|Pedro Antunes|Activo|21/06/2018|Entrada do processo|Observações do evento|26/06/2018|Prazo para resposta