数据库每条数据有商户id字段、数量number字段、时间createtime字段 现在要查询近七日每个商户的number总数 根据日期分组 mysql和java实现代码
时间: 2024-02-13 14:02:33 浏览: 198
关于日期的处理包括java和sql
5星 · 资源好评率100%
MySQL查询语句如下:
```
SELECT
merchant_id,
DATE_FORMAT(createtime, '%Y-%m-%d') as date,
SUM(number) as total_number
FROM
your_table_name
WHERE
createtime >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)
GROUP BY
merchant_id, date;
```
上面的查询语句会返回每个商户在过去七天内每天的number总数。
Java代码实现如下:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class TotalNumberByMerchant {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
String sql = "SELECT merchant_id, DATE_FORMAT(createtime, '%Y-%m-%d') as date, SUM(number) as total_number "
+ "FROM your_table_name "
+ "WHERE createtime >= ? "
+ "GROUP BY merchant_id, date";
PreparedStatement pstmt = conn.prepareStatement(sql);
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date today = new Date();
cal.setTime(today);
cal.add(Calendar.DATE, -7);
Date lastWeek = cal.getTime();
pstmt.setString(1, sdf.format(lastWeek));
ResultSet rs = pstmt.executeQuery();
List<TotalNumberByMerchantDTO> list = new ArrayList<>();
while (rs.next()) {
TotalNumberByMerchantDTO dto = new TotalNumberByMerchantDTO();
dto.setMerchantId(rs.getInt("merchant_id"));
dto.setDate(rs.getString("date"));
dto.setTotalNumber(rs.getInt("total_number"));
list.add(dto);
}
System.out.println(list);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
class TotalNumberByMerchantDTO {
private int merchantId;
private String date;
private int totalNumber;
public int getMerchantId() {
return merchantId;
}
public void setMerchantId(int merchantId) {
this.merchantId = merchantId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getTotalNumber() {
return totalNumber;
}
public void setTotalNumber(int totalNumber) {
this.totalNumber = totalNumber;
}
@Override
public String toString() {
return "TotalNumberByMerchantDTO [merchantId=" + merchantId + ", date=" + date + ", totalNumber=" + totalNumber
+ "]";
}
}
```
上面的Java代码会连接到MySQL数据库并执行上述查询语句,将结果封装成DTO并输出到控制台。请将代码中的`your_database_name`、`your_username`、`your_password`、`your_table_name`替换为实际的数据库名、用户名、密码和表名。
阅读全文