Domanda

ho qualcosa di simile la seguente struttura dei dati:

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

Voglio che il min StartDateTime e max data_ora_fine per ogni categoria. In questo modo:

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

Utilizzando min & max con un gruppo per categoria non sembra funzionare:

select
    Category,
    min(StartDateTime) [MinStartDateTime],
    max(EndDateTime) [MaxDateTime]
from
    MyTable
group by
    Category
order by
    Category,
    StartDateTime,
    EndDateTime

Ho provato anche due inner join su un sub-query per ogni min e max dichiarazione, tuttavia, sembra essere escluso alcuni record:

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

Tutte le idee? Il database è Sybase ASE che dovrebbe essere SQL-92.

È stato utile?

Soluzione

La prima soluzione sembra corretto, tranne per l'ordine dalla clausola; provare:

select
    Category,
    min(StartDateTime) [MinStartDateTime],
    max(EndDateTime) [MaxDateTime]
from MyTable
group by
    Category
order by
    Category,
    MinStartDateTime,
    MaxDateTime
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top