如何在日期间隔内计算数据

时间:2014-01-07 08:27:25

标签: sql count intervals

我想制作highcharts的图表,计算过去12个月内销售的产品数量。

例如: 今天是1月7日

假设我的sql表是这样的:

DATE           SOLD
feb-6           5
feb-8           7
mar-10          15
mar-30          1
apr-1           6
and so on..

所以sql必须像这样产生: feb = 12,mar = 16,apr = ....依此类推,直到本月。有人可以帮帮我吗?因为我不知道如何编写正确的sql代码。

这是我的javascript:

$(document).ready(function() {
    options = {
    chart: {renderTo: 'chart', type: 'line', marginRight: 130, marginBottom: 25},
    credits: {enabled: false},
    title: {text: 'Sales Performance', x: -20},
    xAxis: {categories: [{}]},
    yAxis: {title: {text: 'sold'}, plotLines: [{value: 0,width: 1,color: '#808080'}]},
    legend: {layout: 'vertical', align: 'right', verticalAlign: 'top', x: -10, y: 100, borderWidth: 0},
    tooltip: {
        formatter: function() {
            var s = '<b>'+ this.x +'</b>';
            $.each(this.points, function(i, point) {
                s += '<br/>'+point.series.name+': '+point.y;
            });
            return s;
        },
        shared: true
    },
    series: [{},{}]
};
$.ajax({
    url: "generate_graph",
    data: 'date='+dateText,
    type: 'post',
    dataType: "json",
    success: function(data){
        options.xAxis.categories = data.categories;
            options.series[0].name = data.name;
            options.series[0].data = data.value;
        var chart = new Highcharts.Chart(options);          
    }
    });
})

2 个答案:

答案 0 :(得分:1)

我刚回答sql查询:

select
  month(solddate), 
  sum(sold)
from 
  selling
where solddate between date_sub(now(), interval 1 year) and now()
group by month(solddate);

参见 SQLFIDDLE

答案 1 :(得分:1)

您可能需要查看此内容:MySQL Query GROUP BY day / month / year

Answer:

GROUP BY YEAR(record_date), MONTH(record_date)