2

//嗨我有这个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 循环和临时变量,但我认为必须有更好的方法?

4

3 回答 3

0

使用聚合函数和分组:

SELECT SUM(price), endDate FROM table GROUP BY endDate;
于 2012-11-28T11:10:35.410 回答
0

我认为这会做正确的把戏

SELECT YEAR(startDate)year, MONTH(startDate)month, SUM(price)price FROM table GROUP BY MONTH(startDate)
于 2012-11-28T11:28:00.167 回答
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();
}
于 2012-11-28T12:31:55.953 回答