用mysql 查询一年内每个月的数据 怎么写

用mysql 查询一年内每个月的数据 怎么写,第1张

select * from 表 where date_format(日期,'%Y-%m-%d')='2014-04-01' 日期

select * from 表 where date_format(日期,'%Y-%m')='2014-04' 月份

select * from 表 where date_format(日期,'%Y')='2014' 年

就是date_format(日期,'%Y-%m-%d') 这里的参数长短

$sql=mysql_query("select * from biao where creattime>=1 and creattime <=3")

while($row=mysql_fetch_array($sql))

{

echo $row['people']."<br>"

}

日期改成自己的就ok了,有用记得采纳哦

数据表中不存在的月份也要显示,建议创建一个从1到12月份的表作为比对表。如果不方便创建月份比对表则可以用select 1到12的办法来虚拟这个月份比对表,但是语句会有些冗长。请参考下列写法:

select months.year,months.month, 

concat(ifnull(t.sumMonthNum,'0'),

'/',months.sumYearNum) as `月/年比`

from 

(select * from 

(select year(time) as year,

sum(num) as sumYearNum 

from abc group by year(time)) years, 

(select 1 as month union all 

select 2 union all 

select 3 union all 

select 4 union all 

select 5 union all 

select 6 union all 

select 7 union all 

select 8 union all 

select 9 union all 

select 10 union all 

select 11 union all 

select 12) months) months left join 

(select year(time) as year,

month(time) as month,

sum(num) as sumMonthNum 

from abc group by year(time),month(time)) t 

on months.month=t.month 

order by months.year,months.month

实验截图如下:

源表数据

SQL代码及运行结果


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/8629999.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-19
下一篇2023-04-19

发表评论

登录后才能评论

评论列表(0条)

    保存