1
3 tables: Processo
, Evento
, Alerta
The goal is to make a query that returns all processes by adding the columns of the most recent event type and date MAX(DataEvento)
and the next warning (shorter date longer than the current date) and warning remarks.
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
List 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 comes 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 processes each one appears once and the query fields are presented, adding the date, type and observations of the last event and the date and observations of the next alert, example:
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
passes the table structure please
– Rovann Linhalis
The tables are bigger actually, I simplified here to ask the question...
– OMB
look at this: https://www.db-fiddle.com/f/xzzMqmDGQe6TXFg9LchNqw/0
– Rovann Linhalis
Yes, list correctly, however it is T-SQL and does not have the issue of alert. The alert is associated with the event and each event can have 1 or several alerts, I need to list the lowest alert date higher than the current date. I will try to adapt this solution, I believe that these details cause some confusion in the syntax, when I get put here
– OMB