SQL min / max grupo por causa
-
11-09-2019 - |
Pergunta
Eu tenho algo como o seguinte estrutura de dados:
Category StartDateTime EndDateTime =============================================== 1 12/1/2009 12:00 12/1/2009 12:12 1 12/1/2009 04:00 12/1/2009 04:20 2 12/2/2009 10:15 12/2/2009 10:22 2 12/2/2009 11:00 12/2/2009 11:01
Eu quero o min StartDateTime e EndDateTime máximo para cada categoria. Como esta:
Category MinStartDateTime MaxEndDateTime =============================================== 1 12/1/2009 12:00 12/1/2009 04:20 2 12/2/2009 10:15 12/2/2009 11:01
Usando min & max com um grupo por categoria não parece trabalho:
select
Category,
min(StartDateTime) [MinStartDateTime],
max(EndDateTime) [MaxDateTime]
from
MyTable
group by
Category
order by
Category,
StartDateTime,
EndDateTime
Eu também tentei duas associações internas em uma sub-consulta para cada min e declaração max, no entanto, parece estar excluindo alguns registros:
select distinct
T1.Category,
T1.StartDateTime [MinStartDateTime],
T1.EndDateTime [MaxEndDateTime]
from
MyTable T1
inner join
(select
Category,
min(StartDateTime) [MinStartDateTime]
from
MyTable
group by
Category) T2
on T2.Category = T1.Category and T2.MinStartDateTime = T1.StartDateTime
inner join
(select
Category,
max(EndDateTime) [MaxEndDateTime]
from
MyTable
group by
Category) T3
on T3.Category = T1.Category and T3.MaxEndDateTime = T1.EndDateTime
order by
T1.Category,
T1.encodeStartDateTime,
T1.encodeEndDateTime
Todas as idéias? O banco de dados é Sybase ASE que deve ser SQL-92 compatível.
Solução
A sua primeira solução parece correto, exceto para o fim da cláusula; tente:
select
Category,
min(StartDateTime) [MinStartDateTime],
max(EndDateTime) [MaxDateTime]
from MyTable
group by
Category
order by
Category,
MinStartDateTime,
MaxDateTime
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow