sql 獲取最近7天的每日數據


第一步:查詢一定范圍內的數據、數量
查詢最近一天的數據:

select * from table where to_days(column_time) = to_days(now());
select * from table where date(column_time) = curdate(); 
查詢最近一周的數據

select * from "table"  where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date("column_time");
語句解析     
① :CURRENT_DATE:以‘YYYY-MM-DD’或YYYYMMDD格式返回今天日期值,取決於函數在一個字符串還是數字上下文被使用。select CURTIME(); 
② :DATE_SUB(date,INTERVAL expr type) ,進行日期減少的操作,可以精確到秒
查詢最近一個月的數據:

select * from table  where DATE_SUB(CURDATE(), INTERVAL INTERVAL 1 MONTH) <= date(column_time);
第二步:統計一定范圍內,每個單位內的數量【單位可以天,月、周、年、等】
1)按天統計:

select DATE_FORMAT(start_time,'%Y%-m-%d') days,count(*) count from xxxx group by days; 
2)按周統計:

select DATE_FORMAT(start_time,'%Y-%u') weeks,count(*) count from xxxx group by weeks; 
3)按月統計:

  select DATE_FORMAT(start_time,'%Y-%m') months,count(*) count from xxxx group by months; 
 

第三步:統計最近七天內的數據並按天分組  
思路:將查詢范圍的數據作為一張虛表,也就是  統計SQL的數據源即可。

SELECT
DATE_FORMAT( "時間列名", '%Y-%m-%d' ) days,
count(*) count
FROM

( SELECT * FROM "表名"
WHERE DATE_SUB( CURDATE( ), INTERVAL 7 DAY ) <= date( "時間列名") ) as "表別名"

GROUP BY
days;

 

 

https://blog.csdn.net/Sugar_map/article/details/83857449

 

https://blog.csdn.net/qq_24024541/article/details/103616481

 

 

 

count 里面加條件

SELECT handler,count(case status when 1 then 1 else null end) as count from home_jb_ww_sh GROUP BY handler

https://www.cnblogs.com/yszzu/p/10430483.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM