如何在一天中的两个不同时间之间获取记录,同时在同一个表中包含其他日期数据

时间:2017-11-23 09:34:49

标签: sql

如何在一天内的两个不同时间之间获取记录,同时在同一个表中包含其他日期数据。

表:

id reported_date         dept
1  2017-11-23 09:00:05   IT
2  2017-11-22 21:00:10   IT
3  2017-11-23 10:00:09   SC
4  2017-11-22 22:00:20   SC
5  2017-11-23 05:00:30   IT

以上数据基于以下标准捕获:晚上8:00(昨天) - 晚上8:00(今天) - 将在今天的桌子上。

现在我想标记数据,如果它是在晚上8点(前一天) - 上午6点(今天)之间为'晚'。作为新列或临时变量。

在上表中,2,4,5的记录将被标记为“延迟”,但您不应手动将时间范围用作8-6。在晚上8:00之后的最短时间记录和早上6:00之前的最长时间记录。 请帮帮我。

2 个答案:

答案 0 :(得分:1)

SELECT *
FROM tablename
WHERE hour(reported_date)<6 or
      hour(reported_date)>20

答案 1 :(得分:0)

用mysql修改和编写的答案

/*SET @TODAY_TIMESTAMP = CURRENT_TIMESTAMP;*/ /*use this for live code*/
SET @TODAY_TIMESTAMP = '2017-11-23 14:27:10'; /*just for test scenary date of question was posed on */
SET @YesterdayEightPM = concat_ws(' ', DATE( DATE_ADD(@TODAY_TIMESTAMP, interval -1 day)),  ' 20:00:00'); 
SET @TodaySixAm  = concat_ws(' ', DATE(@TODAY_TIMESTAMP), '06:00:00');

CREATE temporary table  IF NOT EXISTS TBL_TEMP
( 
    id int,
    reported_date DATETIME,    
    dept varchar(40)
);

DELETE FROM TBL_TEMP where 1=1;

INSERT INTO TBL_TEMP (id,reported_date,dept)
VALUES (1,'2017-11-23 09:00:05', 'IT'),
       (2,'2017-11-22 21:00:10','IT'),
       (3,'2017-11-23 10:00:09','SC'),
       (4,'2017-11-22 22:00:20','SC'),
       (5,'2017-11-23 05:00:30','IT');   

SELECT ID, reported_date, dept,
       CASE WHEN reported_date BETWEEN CAST(@YesterdayEightPM AS DATETIME) AND CAST(@TodaySixAm AS DATETIME) THEN 'Late'                                       
       ELSE  'Normal' END AS 'Type',
       @TODAY_TIMESTAMP As TODAY_TIMESTAMP, 
       @YesterdayEightPM AS Yesterday8PM, 
       @TodaySixAm AS Today6AM
FROM TBL_TEMP;

用sql server编写的原始答案

DECLARE @TODAY_TIMESTAMP DATE = CURRENT_TIMESTAMP
DECLARE @YesterdayEightPM DATETIME = CAST(DATEADD(DD, -1,@TODAY_TIMESTAMP) as varchar(50)) + ' 20:00:00.000'
DECLARE @TodaySixAm DATETIME = CAST(@TODAY_TIMESTAMP as varchar(50)) + ' 06:00:00.000'

SELECT @YesterdayEightPM AS Yesterday8PM, @TodaySixAm AS Today6AM

DECLARE @TBL_TEMP TABLE 
( 
    [id] [int] NOT NULL,
    [reported_date] [DATETIME] NOT NULL,    
    [dept] [varchar](40) NULL   
)

INSERT INTO @TBL_TEMP (ID, reported_date, dept)
VALUES  (1,'2017-11-23 09:00:05', 'IT'),
        (2,'2017-11-22 21:00:10','IT'),
        (3,'2017-11-23 10:00:09','SC'),
        (4,'2017-11-22 22:00:20','SC'),
        (5,'2017-11-23 05:00:30','IT')

SELECT  ID, reported_date, dept,
        CASE WHEN TT.reported_date BETWEEN     @YesterdayEightPM AND @TodaySixAm THEN 'Late'
        ELSE 'Normal'END
FROM @TBL_TEMP TT   WHERE 1=1