简体   繁体   English

如何使用Mysql语句分隔日夜记录

[英]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 在我的SQL数据库中,我将带有时间戳的日期存储为这样的示例(2015-09-21 18:02:14)我要求使用SQL语句获取上次时间(18:02:14)是Day还是Night

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 在我的表中,如果有20条记录相同的日期,则仅获得日记录如何创建查询

If the day defines from 6am to 6pm, Then 如果日期定义为上午6点至下午6点,则

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. 然后,您可以使用DATE_FORMAT函数将datetime字段转换为HH:MI字符串。

For example you can select records from 18:00 to 8:00 (Night) 例如,您可以选择18:00到8:00(晚上)之间的记录

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

SQLFiddle demo SQLFiddle演示

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. 您可以在添加到表之前进行比较(并创建另一个名为isDay的列),或者从表中进行选择时进行比较。

Note: 注意:

  1. Sunset/Sunrise times depend on your geo-location. 日落/日出时间取决于您的地理位置。

  2. There are API's that can provide that info 有可以提供该信息的API

  3. There are algorithms that can assist in calculating that info 有一些算法可以帮助计算该信息

Examples: 例子:

  1. http://sunrise-sunset.org/api http://sunrise-sunset.org/api
  2. http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2015-12-13 http://api.sunrise-sunset.org/json?lat=36.7201600&lng=-4.4203400&date=2015-12-13
  3. I need a sunrise/sunset webservice api 我需要日出/日落Web服务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 18 = 6PM,可以用DATETIME列替换GETDATE()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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