时间:2014-10-17 09:54:57 来源: 复制分享
做一个自动任务,需要查询指定期限内数据,比如按照自然月,按照自然日,按照自然周,需要支持Oracle 和 SqlServer数据库。
数据库中表字段receivetime,由C++负责写入,内容为time_t的32位值,也就是1970年到现在的秒数。
研究了一天,得出如下语句:
对于SqlServer,
查询前一天的数据,
select * from table_name where datediff ( day, dateadd(day, (ReceiveTime+8*3600)/60/60/24 - 1, '19700101'), getdate() ) = 2;
请关注其中的8*3600,这是因为,SqlServer中,按照UTC计算标准时间,(ReceiveTime)/60/60/24计算的标准时间,但是数据库服务器时区是东八区,故需要加上这个值。
以下同理,不解释。
查询前一周的数据,
查询前一周
SELECT *
FROM tablename
WHERE datediff
(day,
dateadd
(day,
(ReceiveTime + 8 * 3600) / 60 / 60 / 24,
'1970-01-01 00:00:00'),
getdate ()) >= DatePart (Weekday, getdate ()) + 1
and
datediff
(day,
dateadd
(day,
(ReceiveTime + 8 * 3600) / 60 / 60 / 24,
'1970-01-01 00:00:00'),
getdate ()) <= DatePart (Weekday, getdate ()) + 8;
查询前一月的数据,
查询前一月
SELECT *
FROM tablename
WHERE datediff
(month,
dateadd
(day,
(ReceiveTime + 8 * 3600) / 60 / 60 / 24,
'1970-01-01 00:00:00'),
getdate ()) = 1;
对于Oracle数据库
查询前一天:
查询前一天
SELECT count(*)
FROM tablename
WHERE receivetime >=
((TRUNC (SYSDATE - 1, 'dd') - TO_DATE ('19700101', 'yyyymmdd')
)
* 24
* 3600 - 8 * 3600)
AND receivetime <
( (TRUNC (SYSDATE, 'dd') - TO_DATE ('19700101', 'yyyymmdd')
) * 24 * 3600 - 8 * 3600);
查询前一周:
查询前一周
SELECT count(*)
FROM tablename
WHERE receivetime <
( ( TRUNC (SYSDATE - TO_NUMBER (TO_CHAR (SYSDATE, 'W')) , 'dd')
- TO_DATE ('19700101', 'yyyymmdd')
)
* 24
* 3600 - 8 * 3600 )
AND receivetime >=
(( TRUNC (SYSDATE - TO_NUMBER (TO_CHAR (SYSDATE, 'W')) - 7, 'dd')
- TO_DATE ('19700101', 'yyyymmdd')
)
* 24
* 3600 - 8 * 3600 );
查询前一月:
查询前一月
SELECT count(*)
FROM tablename
WHERE receivetime >=
( ((trunc(last_day( add_months(sysdate, -2 )),'dd') + 1) - TO_DATE ('19700101', 'yyyymmdd')) * 24 * 3600 - 8 * 3600 )
AND receivetime < (((trunc(last_day( add_months(sysdate, -1 )),'dd') + 1) - TO_DATE ('19700101', 'yyyymmdd')) * 24 * 3600 - 8 * 3600);