thinkphp mysql统计问题
不用循环去查,一次分组查询就可以了
$dates = array();
$endDate = strtotime('2014-12-27');
for($i = 7; $i > 0; $i--) {
$dates[] = "select '".date( 'Y-m-d', strtotime("-{$i} day", $endDate) )."' as date";
}
$dd = M()->table(M()->table("(".join(' union ', $dates).") a")
->join('__PRODUCT_SELL__ b on a.date = left(b.consumpTime, 10)', "LEFT")
->select(false)." a")
->field("a.date,(case sum(a.productPrice) when sum(a.productPrice) then sum(a.productPrice) else 0 end) sum")
->group("a.date")
->select();
dump($dd);
查询结果:
array(7) {
[0] => array(2) {
["date"] => string(10) "2014-12-20"
["sum"] => string(1) "0"
}
[1] => array(2) {
["date"] => string(10) "2014-12-21"
["sum"] => string(1) "0"
}
[2] => array(2) {
["date"] => string(10) "2014-12-22"
["sum"] => string(1) "0"
}
[3] => array(2) {
["date"] => string(10) "2014-12-23"
["sum"] => string(1) "0"
}
[4] => array(2) {
["date"] => string(10) "2014-12-24"
["sum"] => string(2) "45"
}
[5] => array(2) {
["date"] => string(10) "2014-12-25"
["sum"] => string(2) "24"
}
[6] => array(2) {
["date"] => string(10) "2014-12-26"
["sum"] => string(1) "0"
}
}