1. 程式人生 > >常用sql集合

常用sql集合

1.按照年份月份拆分欄位,並統計。

SELECT DATE_FORMAT(creat_time,"%Y年%m月") AS dates,COUNT(*) FROM ssoml.mlcp_node GROUP BY 
 DATE_FORMAT(creat_time,"%Y年%m月")
 ORDER BY DATE_FORMAT(creat_time,"%Y年%m月") DESC ;

如圖:

 

2.如上圖表:

問題:我要求每個月新增了幾條資料,截止當前月份共有幾條資料

select tt.dates AS 時間,tt.counts AS 本月新增, 
(select count(*) from mlcp_node where creat_time<=a.creat_time- interval 0 day) as 截止本月前共有實驗
 from mlcp_node a ,
((SELECT DATE_FORMAT(creat_time,'%Y年%m月') AS dates,COUNT(*) AS counts FROM ssoml.mlcp_node GROUP BY 
 DATE_FORMAT(creat_time,'%Y年%m月')
 ORDER BY DATE_FORMAT(creat_time,'%Y年%m月') DESC)) tt where DATE_FORMAT(a.creat_time,'%Y年%m月')=tt.dates
GROUP BY tt.dates
ORDER BY creat_time DESC;

 

 

 

 

3.(該條為轉載 連結 https://blog.csdn.net/chengzhewang/article/details/42918703)

查詢今天的記錄:

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

查詢昨天的記錄:

select * from story where to_days(now()) - to_days(create_time) = 1;

查詢近7天的資訊記錄:

select * from story where DATE_SUB(CURDATE(),INTERVAL 7 DAY) <= DATE(create_time);

查詢近30天的資訊記錄:

select * from story where DATE_SUB(CURDATE(),INTERVAL 30 DAY) <= DATE(create_time);

查詢本月的資訊記錄:

select * from story where DATE_FORMAT(create_time,'%Y-%m') = DATE_FORMAT(CURDATE(),'%Y-%m');

查詢上月的資訊記錄:

select * from story where PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y-%M'),DATE_FORMAT(create_time,'%Y-%m')) = 1;