根据结束日期每月有效订阅?

时间:2012-11-28 11:08:15

标签: php mysql

//我有这个mysql表

id    price     startDate     endDate

1     200       2012-01-10   2012-03-15 
2     250       2012-02-15   2012-03-18 
3     100       2012-02-11   2012-02-20 
4     260       2012-03-22   2012-04-15 

我想要的是按月间隔获得订阅的总收入,以便输出

201201    200
201202    550     //(250 + 200 + 100)
201203    710     //(260 + 200 + 250)
201204    260

我自己对此有所了解是基于很多php循环和临时变量,但我认为必须有更好的方法吗?

3 个答案:

答案 0 :(得分:0)

使用聚合函数和分组:

SELECT SUM(price), endDate FROM table GROUP BY endDate;

答案 1 :(得分:0)

我认为这会做出正确的伎俩

SELECT YEAR(startDate)year, MONTH(startDate)month, SUM(price)price FROM table GROUP BY MONTH(startDate)

答案 2 :(得分:0)

我会再试一次,但这会有多个查询:

$totalMonths = ($maxDateYear - $minDateYear) * 12 - $minDateMonth + $maxDateMonth;
$year = $minDateYear;
$month = $minDateMonth;
$st = $pdo->prepare("SELECT SUM(price) FROM table WHERE startDate < ? and endDate >= ?");

for ($i = 0; $i < $totalMonths; $i++) {
    $date1 = "$year-$month-01";
    if (++$month > 12) { $month = 1; $year++; }
    $date2 = "$year-$month-01";
    $st->execute(array($date2, $date1));
    echo "$date1: " . $st->fetchColumn();
}