根据时间段,mysql 把日期作为列名.统计 java 拼接sql

import java.text.*;
import java.util.Date;
 
public class Hello {
    String dateFormat = "yyyy-MM-dd";
    SimpleDateFormat format = new SimpleDateFormat(dateFormat);
 
    public static void main(String[] args) {
        Hello t = new Hello();
 
        String date1 = "2018-10-15";
        String date2 = "2018-10-21";
 
        t.process(date1, date2);
    }
 
    private void process(String date1, String date2){
        if(date1.equals(date2)){
            System.out.println("两个日期相等!");
            return;
        }
 
        String tmp;
        String sql1 = "";
        if(date1.compareTo(date2) > 0){  //确保 date1的日期不晚于date2
            tmp = date1; date1 = date2; date2 = tmp;
        }
 
        tmp = format.format(str2Date(date1).getTime() + 3600*24*1000);
 
        int num = 0;
        while(tmp.compareTo(date2) < 0){                   
            
        System.out.println(tmp);    
             
         sql1 = sql1+" SUM(IF(DATE_FORMAT(createtime,"+ "\"%Y-%m-%d\"" +") =" +
        "'"+tmp+"'"+", male+female, 0)) AS " +"'"+tmp+"'"+"," ;
           
            num++;
            tmp = format.format(str2Date(tmp).getTime() + 3600*24*1000);
         
        }
        //
        sql1="SELECT wokstationid, male+female,createtime, " +
        sql1+ " createtime " +
         " FROM t_b_events WHERE createtime > '2018-10-17' AND createtime < '2019-01-01'  AND wokstationid=145";
 
         System.out.println(sql1);
        if(num == 0)
            System.out.println("两个日期相邻!");
    }
 
private Date str2Date(String str) {
        if (str == null) return null;
 
        try {
            return format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

 

/*

格式:

id    male    2018-10-1      2018-10-2     2018-10-3

1     2           3                         1                  2

2      1           1                        0                 8

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值