数据库日期记录按周,月,3个月使用数据库查询或php


Database date records ordered by week, month, 3-month using db query or php?

我有一个包含会员付款记录的数据库。像这样:

    Payment Date     |   Amount
---------------------------------
2014-02-01 00:00:00  |     10
2014-02-21 00:00:00  |     10
2014-07-22 00:00:00  |     10
2014-08-16 00:00:00  |     10
2014-11-23 00:00:00  |     10
2015-03-17 00:00:00  |     10
2015-04-30 00:00:00  |     10
2015-06-11 00:00:00  |     10
2015-07-11 00:00:00  |     10

付款金额可以变化,但不会总是'10'。

我需要按周、月、月、年的付款记录,但要有金额和周期的开始。

例如按年份,我需要得到:

2014-01-01 00:00:00 - 50   //timestamp of beginning of the year
2015-01-01 00:00:00 - 40   //and the sum of payments that year

同样,对于季度记录,我需要得到:

2014-01-01 00:00:00 - 20   //timestamp of beginning 
2014-04-01 00:00:00 -  0   //of the trimester
2014-07-01 00:00:00 - 20   //and the sum of the payments
2014-10-01 00:00:00 - 10   //that trimester
2015-01-01 00:00:00 - 10   //timestamp of beginning 
2015-04-01 00:00:00 - 20   //of the trimester
2015-07-01 00:00:00 - 10   //and the sum of the payments that trimester

为了解决这个问题,我正在考虑两种可能的方法:

1) Put together a mysql query (if it possibly exists) 
2) Get all the records from the user and just sort them with php

我准备去为php解决方案,但有一种方式,它可以完成与mysql查询?如果是这样,你能告诉我完成这个查询的路径吗?

另外,哪种解决方案更有效/更省时?

您可以使用WEEK(), MONTH(), QUARTER()等函数获得这些组。这里有一个完整的日期和时间函数列表。

要获得每年的计数,您可以这样做:

SELECT YEAR(paymentDate), SUM(amount) AS totalAmount
FROM myTable
GROUP BY YEAR(paymentDate);

然后,您可以使用MAKEDATE函数获得一年的第一天:

SELECT MAKEDATE(YEAR(paymentDate), 1);

您可能必须使用DATE_FORMAT来配置一个月/季度的第一天,但是您可以在我分享的链接中找到必要的功能。