根據日期查詢的一些sql

2021-10-25 22:07:46 字數 1395 閱讀 2841

文章

發布於2023年7月14日

根據日期查詢的一些sql

查詢資料

查詢上個月的資料

select * fromcount_referralwhere period_diff(date_format(now(),』%y%m』), date_format(update_time,』%y%m』)) =1;

​查詢本月資料

select * fromcount_referralwhere date_format(create_time, 『%y%m』) = date_format(curdate(), 『%y%m』);

​查詢上個季度的資料

select * fromcount_referralwhere q

uarter(create_time)=quarter(date_sub(now(),interval 1 quarter));

查詢去年的資料

select * fromcount_referralwhere year(create_time)=year(date_sub(now(),interval 1 year));

查詢當天的資料

select * fromcount_referralwhere to_days(create_time) = to_days(now());

​查詢昨天的資料

select * fromcount_referralwhere to_days(now()) - to_days(create_time) = 1;

​查詢最近7天的資料

select * fromcount_referralwhere date_sub(curdate(), interval 7 day) < date(create_time);

查詢最近30天的資料 包括今天一共30天

select * fromcount_referralwhere date_sub(curdate(), interval 30 day) < date(create_time);

總結:1.year(),從時間字段獲取年

2.quarter(),從時間字段獲取季度

3.month(),從時間字段獲取月

4.week(),從時間字段獲取周

5.yearweek(),從時間字段獲取年和周

6.date_sub(), 從時間字段減去指定時間間隔

7.date_format(),時間格式化

8.to_days(),返回從0年開始的天數;

9.from_days(),根據天數,返回日期;

10.curdate() 函式返回當前的日期。

根據最近日期查詢的sql

幾個小時內的資料 date sub now interval 5 hour 今天select from 表名 where to days 時間欄位名 to days now 昨天select from 表名 where to days now to days 時間欄位名 1 7天select fro...

SQL高階查詢的一些技巧

高階查詢的一些技巧 1.使用and時,盡量將很可能不為真的條件放在前面 2.使用or運算子時,盡量將最可能為真的條件放在前面 3.distinct比order by更快 select memberid from orders group by memberid select distinct mem...

sql一些簡單的查詢語句

1.查詢今天的資料 select from 函式名 字段,getdate 2.查詢昨天的資料 select from 函式名 字段,dateadd day,1,getdate 3.查詢前天的資料 select from 函式名 字段,dateadd day,2,getdate 4.查詢本月的資料 d...