你的方法只适用于一年;否则,如果您不希望将多年中的月份组合在一起,则需要额外的列。您还应该使用date
函数而不是检查整数值(您不应该将日期存储为 int)。
如果您需要动态方法,则需要在 PHP 端进行动态查询准备(获取开始/结束日期并生成 SQL)。
这可能是您正在寻找的解决方案:
<?php
$startDate = '201201';
$endDate = '201303';
$formattedStartDate = strtotime( SUBSTR($startDate, 0, 4) . '-' . SUBSTR($startDate, -2, 2) . '-01' );
$formattedEndDate = strtotime( SUBSTR($endDate, 0, 4) . '-' . SUBSTR($endDate, -2, 2) . '-01' );
$sql = "SELECT SellerName, \n";
while ($formattedStartDate <= $formattedEndDate) {
$sql .= 'SUM(IF(LEFT(ReportMonth, 4) = ' . date('Y', $formattedStartDate) . ' AND RIGHT(ReportMonth, 2) = ' . date('m', $formattedStartDate) . ")) AS '" . date('M Y', $formattedStartDate);
if($formattedStartDate <> $formattedEndDate) {
$sql .= "', \n";
}
else {
$sql .= "'\n";
}
$formattedStartDate = strtotime('+1 month', $formattedStartDate);
}
$sql .= 'COUNT(*) AS YTD
FROM onlineDATA
WHERE BuyerZipCode IN ($zips_query)
GROUP BY SellerName';
echo $sql;
结果
选择卖家姓名,
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 01)) AS 'Jan 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 02)) AS 'Feb 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 03)) AS 'Mar 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 04)) AS 'Apr 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 05)) AS 'May 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 06)) AS 'Jun 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 07)) AS 'Jul 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 08)) AS 'Aug 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 09)) AS 'Sep 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 10)) AS 'Oct 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 11)) AS 'Nov 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2012 AND RIGHT(ReportMonth, 2) = 12)) AS 'Dec 2012',
SUM(IF(LEFT(ReportMonth, 4) = 2013 AND RIGHT(ReportMonth, 2) = 01)) AS 'Jan 2013',
SUM(IF(LEFT(ReportMonth, 4) = 2013 AND RIGHT(ReportMonth, 2) = 02)) AS 'Feb 2013',
SUM(IF(LEFT(ReportMonth, 4) = 2013 AND RIGHT(ReportMonth, 2) = 03)) AS 'Mar 2013'
计数(*) 为年初至今
来自在线数据
WHERE BuyerZipCode IN ($zips_query)
按卖家名称分组
查看演示