How do I group the column with these condiitions

  • Hi All,

    I have a table named gpsdata_history which consists of the fields gps_datetime and registrationno among various others.

    I want to find the min(gps_datetime) of each vehicle at a particular time span and the max(gps_datetime) of each vehicel at a particular timespan, all these in one single query.

    So it would be like, I want the latest time the vehicle was sending signals on January 1st and the earliest time at which the vehicle started sending signals on January 2 2008

    min(gps_datetime) registrationno max(gps_datetime)

    01/01/2008 3:00:03 abc 01/02/2008 23:00:00

    i gave the query as below

    select max(gps_datetime), registrationno from gpsdata_history where gps_datetime >'07/13/2008' and gps_datetime<'07/14/2008' and analog2='stepii' group by registrationno

    union

    select min(gps_datetime), registrationno from gpsdata_history where gps_datetime >'07/14/2008' and gps_datetime<'07/15/2008' and analog2='stepii' group by registrationno

    But it did not group by registrationno, where am i supposed to rectify

    Kindly help.

    Thanks in advance

    Regards

    cmrhema

  • try this query it may works.

    Select * , (select max(gps_datetime) as maxdate from gpsdata_history where gps_datetime >'07/13/2008' and gps_datetime<'07/14/2008' and analog2='stepii' and registrationno =data.registrationno ) from

    (select min(gps_datetime) as mindate, registrationno from gpsdata_history where gps_datetime >'07/14/2008' and gps_datetime<'07/15/2008' and analog2='stepii' group by registrationno)as data

    Regards

    swamy.

  • Brilliant Swamy, thanks it works.

  • Swamy seems to be very professional for T-SQL! This code is very profi!

    :w00t::w00t::w00t::w00t::w00t:

    ============================================================
    SELECT YOUR PROBLEM FROM SSC.com WHERE PROBLEM DESCRIPTION =
    http://www.sqlservercentral.com/articles/Best+Practices/61537/[/url]

  • Try this for speed

    SELECTRegistrationNo,

    MIN(gps_datetime) AS minTime,

    MAX(gps_datetime) AS maxTime

    FROMgpsdata_history

    WHEREgps_datetime >= '20080713'

    AND gps_datetime < '20080715'

    AND analog2 = 'stepii'

    GROUP BYRegistrationNo

    ORDER BYRegistrationNo


    N 56°04'39.16"
    E 12°55'05.25"

  • HI Peso

    any specific reason for having ORDER BY cluase in the query?

    Thanks -- Vj

  • No.


    N 56°04'39.16"
    E 12°55'05.25"

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply