Mysql和php根据日期从colum获得的值之和
我有一个MYSQL表,其结构如下:Mysql和php根据日期从colum获得的值之和,php,mysql,Php,Mysql,我有一个MYSQL表,其结构如下: select date_format(date, '%Y-%m') as yyyymm, sum(value) from table t where date between $first_date and $second_date group by date_format(date, '%Y-%m') order by yyyymm; 第1列:id 第二栏:日期 第三列:整数值 例如,日期可以从2010年1月1日到2014年12月20日不等 在PHP代码中
select date_format(date, '%Y-%m') as yyyymm, sum(value)
from table t
where date between $first_date and $second_date
group by date_format(date, '%Y-%m')
order by yyyymm;
第1列:id
第二栏:日期
第三列:整数值
例如,日期可以从2010年1月1日到2014年12月20日不等
在PHP代码中,我以Y-m-d格式定义了两个变量,假设值为:
$first_date = "2011-10-17"
$last_date = "2014-11-04"
如何在$first\u date和$last\u date定义的时间间隔内,从第3列中获取每个月的值之和?您可以执行如下SQL查询:
select date_format(date, '%Y-%m') as yyyymm, sum(value)
from table t
where date between $first_date and $second_date
group by date_format(date, '%Y-%m')
order by yyyymm;
我建议您参数化查询,而不是将变量直接放入SQL字符串。您需要一个sumrow,其中mydate介于date1和date2之间?例如:[id=1][date=2011-10-17][value=2];[id=2][date=2011-10-18][value=2];[id=3][date=2011-11-04][value=3];[id=4][date=2011-11-12][value=3];2011-10年度的总额为4;2011-11年度的总额为6;这些是我需要的价值观;在这种情况下,@Gordon的查询将完成我在我的表上尝试的这个查询,该表大约有100个条目,日期从2014-02-14到2014-11-08不等:选择date_formatentry_date,%Y-%m作为yyyyymm,sumactive_entry_值来自active_表,其中条目日期介于2010-10-10和2014-12-12之间,按日期分组,%Y-%m按yyyymm排序的订单。我没有从中得到任何结果。MySQL返回了一个空的结果集,即零行。查询耗时0.0021秒。我不知道我做错了什么。