ORACLE SQL - 如何检查时间是否在特定范围内?

时间:2017-04-27 12:32:06

标签: sql oracle

列'DateTime'以'YYYY / MM / DD HH24:MI:SS'格式显示日期和时间。 我需要只显示在特定范围(2AM - 6AM)有时间的行,而不管具体日期如何。 我有一个代码只显示特定日期的时间范围(凌晨2点到6点)。我需要显示过去7天内的行,时间范围是凌晨2点到6点。

SELECT *
    FROM <table_name >
   WHERE DateTime BETWEEN TO_DATE (
                                    TO_CHAR (TRUNC (SYSDATE), 'DD-MM-YYYY')
                                 || ' '
                                 || '02:00:00',
                                 'DD-MM-YYYY HH24:MI:SS')
                          AND TO_DATE (
                                    TO_CHAR (TRUNC (SYSDATE), 'DD-MM-YYYY')
                                 || ' '
                                 || '06:00:00',
                                 'DD-MM-YYYY HH24:MI:SS')
ORDER BY 1 DESC

5 个答案:

答案 0 :(得分:1)

您需要两个条件:一个是0205之间的小时,另一个是过去七天的一天:

SELECT  *
FROM    <table_name>
WHERE   to_char(DateTime, 'HH') BETWEEN '02' and '05' AND
        DateTime BETWEEN SYSDATE - 7 AND SYSDATE
ORDER BY 1 DESC

答案 1 :(得分:1)

layout(yaxis = list(dtick = 1))

SELECT *
FROM   your_table
WHERE  TO_CHAR( DateTime, 'HH24MMSS' ) BETWEEN '020000' AND '060000'
AND    DateTime >= TRUNC( SYSDATE ) - INTERVAL '7' DAY
AND    DateTime <  TRUNC( SYSDATE ) + INTERVAL '1' DAY

答案 2 :(得分:0)

在这种情况下,我认为最简单的方法是字符串比较:

        // Step 5: Set the preview output
        mVideoMediaRecorder.setPreviewDisplay(mCameraPreview.getSurfaceHolder().getSurface());
        mVideoMediaRecorder.setOrientationHint(mCameraPreview.getPreviewOrientation());

        // Step 6: Prepare configured MediaRecorder
        try {
            mVideoMediaRecorder.prepare();
        } catch (IllegalStateException e) {

注意:介于两者之间,因此这应该可以达到05:59:59。

答案 3 :(得分:0)

SELECT *
    FROM <table_name >
   WHERE DateTime BETWEEN TO_DATE (
                                    TO_CHAR (TRUNC (SYSDATE)-7, 'DD-MM-YYYY')
                                 || ' '
                                 || '02:00:00',
                                 'DD-MM-YYYY HH24:MI:SS')
                          AND TO_DATE (
                                    TO_CHAR (TRUNC (SYSDATE), 'DD-MM-YYYY')
                                 || ' '
                                 || '06:00:00',
                                 'DD-MM-YYYY HH24:MI:SS')

答案 4 :(得分:0)

select * from table_name where to_char(datetime,'HH24') 
between '2' and '6' and to_char(datetime,'dd-mon-yy') 
between to_char(sysdate,'dd-mon-yy')  and to_char(sysdate-7,'dd-mon-yy');