Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time based filtering using sql

I need to select data based on date and time.I have two criteria.How to implement this.

1)select the data between 1-1-2013 and 1-10-2013 with time rage between 10 to 16

2)select the data between 1-1-2013 and 1-10-2013 with time range between 20 to 8 next morning

I implemented a code.Its only working for first criteria.Here is that code.

 where date>='1-1-2013' AND date <'1-10-2013' 
     AND CAST(date AS TIME) between '10:00' and '16:00'

Here the date field in the table is datetime type.Pleases help to solve this

like image 624
Rojish Varughese Avatar asked Oct 21 '25 21:10

Rojish Varughese


2 Answers

1)

WHERE Date Between '2013-01-01 10:00' AND '2013-10-01 16:00'

2)

WHERE Date Between '2013-01-01 20:00' AND '2013-10-01 08:00'
like image 61
Greg Avatar answered Oct 23 '25 12:10

Greg


Try this:

DECLARE @tmp TABLE ( date DATETIME )

INSERT  INTO @tmp
        ( date )
VALUES  ( '2013-01-01 10:09:29'  -- date - datetime
          )
INSERT  INTO @tmp
        ( date )
VALUES  ( '2013-01-01 15:09:29'  -- date - datetime
          )
INSERT  INTO @tmp
        ( date )
VALUES  ( '2013-01-01 17:09:29'  -- date - datetime
          )
INSERT  INTO @tmp
        ( date )
VALUES  ( '2013-01-01 07:09:29'  -- date - datetime
          )
SELECT  date
FROM    @tmp AS t
WHERE   CONVERT(DATE,date) >= CONVERT(DATE, '01-01-2013', 105)
        AND CONVERT(DATE,date) <= CONVERT(DATE, '01-01-2013', 105)
        AND CONVERT(TIME, date) BETWEEN CONVERT(TIME, '10:00')
                                AND     CONVERT(TIME, '16:00')
like image 42
sangram parmar Avatar answered Oct 23 '25 12:10

sangram parmar