报表统计——java实现查询某年某月每天数据,没数据补0

一般图表绘制例如echarts等,返回数据格式都大同小异。重点是利用sql或者java实现数据格式的转型,接下来是关键部分:

1.前提1:提供的工具方法——获取某月有多少天

//通过年份和月份确定该月的最后一天
    public static int getMaxDay(int year,int month ){

        Calendar time=Calendar.getInstance();
        time.clear();
        time.set(Calendar.YEAR,year); //year 为 int 
        time.set(Calendar.MONTH,month-1); //month 为int
         return time.getActualMaximum(Calendar.DAY_OF_MONTH);
    }

2.mapper层sql语句书写

<select id="getAllOrderCountByYearAndMonth" parameterType="pd" resultType="OrderCount" >
        SELECT 
            sum(t.ordercount) ordercount,
            t.[month] month ,
            t.[day] day
        from 
            order t
        where 1=1 
        <if test="year != null and year != ''">
                and t.year=convert(int, #{year}) 
        </if>
        <if test="month != null and month != ''">
                and t.month=convert(int, #{month}) 
        </if>
        GROUP BY 
            t.[month],t.[day]
        HAVING 
            1=1
        ORDER BY t.[day] asc
    </select>

3.service层实现,调用sql返回结果,及对其返回结果进行格式转换(重要)

Map<String,String> resultMap = new HashMap<String,String>();
    //获取到数据库搜索的年份对应某月份的31天订单量
    List<OrderCount> orderCountList = orderCountManager.getAllOrderCountByYearAndMonth(pd);
    //确定某个月的天数(如果日期截止只要到有数据的最大日期,那么可以修改sql语句排列方式,例如,日期从大到小排列,那么就是位置在0上的数据是最大天数,很简单实现,此处不列出来了)
    int days = getMaxDay(Integer.parseInt(pd.get("year").toString()),Integer.parseInt(pd.get("month").toString()));
    //定义vip与常规客户数组
    int[] countVIP = new int[days];
    //将获取到不同年份不同月份不同日期对应不同的订单量放在数组中
    if (orderCountList.size()>0 && orderCountList!=null) {
        for (int i=0;i<orderCountList.size();i++) {
            OrderCount oc = orderCountList.get(i);
            //获取对应天
            if(oc!=null){
                countVIP[oc.getDay()-1] = oc.getOrderCount();
            }
        }
    }
    resultMap.put("orderStatistics", countVIP);

猜你喜欢

转载自www.cnblogs.com/yyk1226/p/10017661.html