【发布时间】:2019-04-11 08:45:26
【问题描述】:
我有这张 MariaDB 表,我想将它用于条形图:
CREATE TABLE `payment_transaction_daily_facts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` date DEFAULT NULL,
`year` int(11) DEFAULT NULL,
`month` int(11) DEFAULT NULL,
`week` int(11) DEFAULT NULL,
`day` int(11) DEFAULT NULL,
`volume` int(11) DEFAULT NULL,
`count` int(11) DEFAULT NULL,
'created_at' date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
在我的示例 SQL 查询中,我有一个日期列。当我将日期、年、月、周和日拆分为不同的列时,如何计算过去 10 天的每日交易量?
最后的结果应该是例如:
Date | Amount| Number of transactions per day |
11-11-2018 | 30 | 3 |
11-12-2018 | 230 | 13 |
我试过了:
SELECT SUM(amount) AS sum_volume, COUNT(*) AS sum_Transactions
WHERE (created_at BETWEEN '2018-11-07' AND '2018-11-08')
GROUP BY DATE(created_at)
我想用 DTO 返回生成的数据:
public class DashboardDTO {
private Date date;
private int sum_volume;
private int sum_Transactions;
... getters and setters
}
休息控制器:
@RestController
@RequestMapping("/dashboard")
public class DashboardController {
private static final Logger LOG = LoggerFactory.getLogger(DashboardController.class);
@Autowired
private DashboardRepository dashboardRepository;
@Autowired
private PaymentTransactionsDailyFactsMapper mapper;
@GetMapping("/volumes")
public ResponseEntity<List<DashboardDTO>> getProcessingVolumes(@PathVariable String start_date, @PathVariable String end_date) {
List<DashboardDTO> list = StreamSupport.stream(dashboardRepository.findPaymentTransactionsDailyFacts(start_date, end_date).spliterator(), false)
.map(mapper::toDTO)
.collect(Collectors.toList());
return ResponseEntity.ok(list);
}
}
JPA 查询:
public List<PaymentTransactionsDailyFacts> findPaymentTransactionsDailyFacts(LocalDateTime start_date, LocalDateTime end_date) {
String hql = "SELECT SUM(amount) AS sum_volume, COUNT(*) AS sum_Transactions " +
" WHERE (created_at BETWEEN :start_date AND :end_date )" +
" GROUP BY DATE(created_at)";
TypedQuery<PaymentTransactionsDailyFacts> query = entityManager.createQuery(hql,
PaymentTransactionsDailyFacts.class).setParameter("start_date", start_date).setParameter("end_date", end_date);
List<PaymentTransactionsDailyFacts> data = query.getResultList();
return data;
}
我应该如何正确实现查询?
当我从 Angular 收到 start_date 和 end_date 作为字符串时,我应该如何将其转换为 LocaDateTime?
【问题讨论】:
-
谢谢,我加了。
-
date列看起来像'2018-11-07'。如果 Angular 破坏了它,就把 Angular 拿开。 -
不影响 Angular 是什么意思?
-
你有太多的信息和不必要的代码和多个问题(如何查询,如何转换日期)。请MCVE.
-
您能否粘贴一些工作示例,以便我对其进行评分?
标签: sql spring spring-boot jpa mariadb