简体   繁体   中英

how to separate Day and Night Record using Mysql Statement

In my SQL database I store date with time stamp for example like this(2015-09-21 18:02:14) I have requirement to get last time(18:02:14) is Day or Night using SQL statement

If you have another idea please share with me. I would like to use it if it fits my requirements.

In my table if have 20 record same date then get only day record how to create query like that

If the day defines from 6am to 6pm, Then

SELECT column
FROM  `tablename` 
WHERE HOUR( column ) 
BETWEEN 6 
AND 18;

First you should define what is a day and night. Then you can use DATE_FORMAT function to convert datetime field to HH:MI string.

For example you can select records from 18:00 to 8:00 (Night)

select * from t 
WHERE DATE_FORMAT(dt, '%H:%i')>='18:00'
      or  DATE_FORMAT(dt, '%H:%i')<'09:00'

SQLFiddle demo

You should have another table (or other data source) that supplies the sunset and sunrise times, then compare you own datetime, to that source. You can compare either before adding to your table (and make another column named isDay) or when SELECTing from the table.

Note:

  1. Sunset/Sunrise times depend on your geo-location.

  2. There are API's that can provide that info

  3. There are algorithms that can assist in calculating that info

Examples:

  1. http://sunrise-sunset.org/api
  2. http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2015-12-13
  3. I need a sunrise/sunset webservice api
-- from sql server 2008 until now
SELECT 
    CASE WHEN DATEPART(HOUR, GETDATE()) < 18 THEN 'DAY'
        ELSE 'NIGHT'
    END

-- from sql server 2012 until now, if you don't like CASE
SELECT IIF(DATEPART(HOUR, GETDATE()) < 18, 'DAY', 'NIGHT')

18 = 6PM you can replace GETDATE() with your DATETIME column

SELECT 
    CASE WHEN DATEPART(HOUR, 'yourDateTimeColumn') < 18 THEN 'DAY'
        ELSE 'NIGHT'
    END AS PeriodOfDay
FROM 'yourTable'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM