Results 1 to 2 of 2
  1. #1
    Join Date
    Aug 2009
    Posts
    1

    Unanswered: Count & Group Records by time interval

    I want to count and group records by Mach from a single table within a specific start and end time with
    an output as shown below.

    Mach Count
    HMach 19
    JMach 12
    GMach 10
    MMach 9
    GMach1 7
    HMach1 6
    HMach2 5
    LMach3 4

    This query generated the above table above:
    SELECT Mach, COUNT(*) AS Count FROM Alarm GROUP BY Mach ORDER BY Count DESC

    but I want add a starting and ending time as:
    (TimeStamp > CONVERT(DATETIME, '2009-08-10 00:00:00', 102)) AND (TimeStamp < CONVERT(DATETIME, '2009-08-12 00:00:00', 102))

    The closest I can get, is this, but I don't want the data grouped by TimeStamp
    SELECT Mach, COUNT(*) AS Count
    FROM Alarms
    GROUP BY Mach, TimeStamp
    HAVING (TimeStamp > CONVERT(DATETIME, '2009-08-10 00:00:00', 102)) AND (TimeStamp < CONVERT(DATETIME, '2009-08-12 00:00:00', 102))
    ORDER BY Count DESC

    Thanks

  2. #2
    Join Date
    Apr 2002
    Location
    Toronto, Canada
    Posts
    20,002
    Code:
    SELECT Mach
         , COUNT(*) AS Count
      FROM Alarms
     WHERE TimeStamp >= '2009-08-10'
       AND TimeStamp  < '2009-08-12'
    GROUP 
        BY Mach
    ORDER 
        BY Count DESC
    rudy.ca | @rudydotca
    Buy my SitePoint book: Simply SQL

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •