根据日期时间列按月和周分组,该列将按每月或每周的第一个分组

时间:2016-09-23 08:36:58

标签: sql group-by

需要按月和周分组,根据每个月或每周的第一个分组的日期时间列,需要对值进行平均。

目前使用的查询没有结果。请帮帮我!

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, [Date]), 0), AVG(Actual), AVG(Planned)
FROM  #Table1
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, [Date]), 0)

样本表数据和按月分组的预期结果:

enter image description here

1 个答案:

答案 0 :(得分:0)

问题尚不清楚,但在实时情况下,我们提取月平均值,这是我做的某种解决方案(假设这是针对MS SQL Server):

public class Data {

String ip, db, un, passwords;
Connection connect;
PreparedStatement stmt;
ResultSet rs;


ArrayList<String> data = new ArrayList<>();
ArrayList<String> data2 = new ArrayList<>();
public Data(){
    ip = "X.X.X.X";
    un = "sa";
    passwords = "1";
    db = "ANKET";

    connect = CONN(un, passwords, db, ip);
    String query = "SELECT Hasta_dosyano,Notlar FROM Hasta";



    try {
        stmt = connect.prepareStatement(query);
        rs = stmt.executeQuery();

        while (rs.next()) {

                String id = rs.getString("Hasta_dosyano");
                String id2 = rs.getString("Hasta_dosyano");
                String full = id + " " + id2;
                String time = rs.getString("Notlar");
                data.add(full);
                data2.add(time);


        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

}

public ArrayList<String> getList() {
    return data;
}
public ArrayList<String> getList2() {
    return data2;
}
public int ListSize() {
    return data.size();
}

@SuppressLint("NewApi")
private Connection CONN(String _user, String _pass, String _DB,
                        String _server) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection conn = null;
    String ConnURL = null;
    try {

        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        ConnURL = "jdbc:jtds:sqlserver://" + _server + ";"
                + "databaseName=" + _DB + ";user=" + _user + ";password="
                + _pass + ";";
        conn = DriverManager.getConnection(ConnURL);
    } catch (SQLException se) {
        Log.e("ERRO", se.getMessage());
    } catch (ClassNotFoundException e) {
        Log.e("ERRO", e.getMessage());
    } catch (Exception e) {
        Log.e("ERRO", e.getMessage());
    }
    return conn;
}
}

我将@Begin和@End作为我的报告参数,以便用户可以决定范围。