7 days a week mysql statistical data and packet

Today writes data to show a project module, ultimate effect is to be presented with a bar graph shows the number of visitors this week, seven days, so give the front end of week seven days of data

For example, today is Tuesday ( actually ), we give the front end of the data Monday Tuesday, Wednesday to Sunday because no back to the data set to 0

The Internet to find some information, are using sql statements directly query method the last seven days of data, this has led to a problem, we'll assume Today is Tuesday, so the statistics is the last Tuesday to today's data, however, I actually last week's data does not need

Here to talk about my own solution, we first look at the mysql DATEDIFF method, which returns the number of days between two date data, such as DATEDIFF ( '2019-8-13', '2019-8-14'), the result returned is 1

So let's write a function

@Select("SELECT count(id) FROM strange_record WHERE DATEDIFF( date_format( now( ) , '%Y-%m-%d' ) , date_format( time, '%Y-%m-%d' ) ) = #{day}")
int getStrangeNumBeforeSomeDays(int day);

If the parameter day = 1, the function returns statistics data one day before

Then we get today is the day of the week

public static int getWeekday(){
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday=c.get(Calendar.DAY_OF_WEEK);
        if(weekday==1)
            return 7;
        else return weekday-1;
    }

In general, the weekday where java is already commonly used method to obtain the current date a few weeks, but returned in java 1 is a Sunday, and so on, 7 Saturday, according to our own habits, I conducted a little change, respectively, 1-7 Monday to Sunday

It is then a simple data processing

@Override
    public Map<String, Object> getStrangeNumCurWeek() {
        Map<String, Object> data = new HashMap<>();
        for(int i=1;i<=7;i++){
            data.put(String.valueOf(i),0);
        }

        int weekday = DateTimeUtil.getWeekday();

        for(int i=1;i<=weekday;i++){
            data.put(String.valueOf(i),monitorIndexDao.getStrangeNumBeforeSomeDays(weekday-i));
        }
        return data;
    }

Finally, this effect is presented

 

Guess you like

Origin www.cnblogs.com/suru723/p/11345700.html