sql时间相关查询

查询当天新增的条数

select * from t_report_info 
where to_days(create_time) = to_days(now());

查询指定时间新增的条数

select * from t_report_info 
where to_days(create_time) = to_days('2023-09-04');

查询30天内新增的条数

select 
date_format(create_time,'%Y-%m-%d') as evertday,
count(*) countNum
FROM t_user_info
GROUP BY evertday 
ORDER BY evertday DESC 
limit 30

查询近30天的数据

select * from t_user_login_record where date_sub(curdate(),interval 30 day) <= date(create_time)

查询本月

select * from t_user_login_record where 
date_format(create_time,'%Y%m') = date_format(curdate() , '%Y%m')

查询上个月

select * from t_user_info where 
period_diff(date_format(now(),'%Y%m') , date_format( create_time,'%Y%m' )) =1

查询本季度数据

select * from t_user_info where quarter(create_time)=quarter(now())

查询上季度数据

select * from t_user_info 
where 
QUARTER(create_time)=quarter(date_sub(now(),interval 1 quarter));

查询本年数据

select * from t_user_info where year(create_time) = year(now())

查询上年数据

select * from t_user_info 
where 
year(create_time)=year(date_sub(now(),interval 1 year))

按月分组

SELECT count(0) as count,DATE_FORMAT( create_time,'%Y-%m') as time 
FROM t_user_info  GROUP BY  time

查询当前这周的数据

select * from t_user_login_record 
where yearweek(date_format(create_time,'%Y-%m-%d')) = yearweek(now())

查询上周数据

select * from t_user_login_record 
where 
yearweek(date_format(create_time,'%Y-%m-%d')) = yearweek(now()) - 1

MySQL获取前 n 天,格式 (yyyy-MM-dd)

SELECT
	@cdate := date_add( @cdate, INTERVAL - 1 DAY ) AS dateStr 
FROM
	( SELECT @cdate := date_add( CURDATE(), INTERVAL + 1 DAY ) 
	FROM t_user_login_record) tmp1 
WHERE
	@cdate > DATE_SUB( CURDATE(), INTERVAL 30 DAY )
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SQL Server中进行时间查询时,以下是一些建议的优化措施。 首先,确保数据库中的日期/时间字段具有适当的索引。对于经常用于时间查询的字段,可以考虑创建一个非聚集索引。这将有助于提高查询性能并加快查询速度。 其次,正确使用日期/时间函数和操作符。避免在WHERE子句中对日期/时间字段进行函数操作,以免影响查询的性能。相反,尽量使用SARG(Search Argument,搜索参数)来进行查询,以便SQL Server可以充分利用索引。 另外,如果查询中包含较长的时间范围,可以考虑进行日期参数的过滤。通过指定合理的起始日期和结束日期来限制查询的范围,可以减少查询的数据量,从而提高查询性能。 此外,注意避免无谓的排序或重复计算。如果查询结果不需要排序,则可以避免使用ORDER BY子句。并且,如果某个查询可能返回重复的结果,可以考虑使用DISTINCT关键字来去除重复项。 另外,考虑分析查询执行计划,以便确定可能存在的性能瓶颈。通过使用SQL Server的性能监视器或其他相关工具,可以查看查询的执行计划,并评估是否需要进一步优化。 最后,仔细评估是否需要使用索引视图或汇总表来改善查询性能。如果有大量的时间查询需求,并且查询结果的数据量较大,可以考虑创建索引视图或汇总表来提前计算和存储结果,以减少查询的工作量。 综上所述,通过正确使用索引、日期过滤、避免无谓的排序和重复计算,以及评估查询执行计划和考虑使用索引视图或汇总表等优化措施,可以提高SQL Server时间查询的性能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值