我尝试过创建临时表来实现这一目标。无论如何我得到了结果,但不准确。
$MarketQry="SELECT DISTINCT `Market` FROM `orders`";
$MarketResult=mysql_query($MarketQry,$con);
$OrdersQry="";
while($mvalue=mysql_fetch_array($MarketResult))
{
$OrdersQry.="CASE WHEN `Market`='".$mvalue['Market']."' THEN SUM(`Count`) ELSE 0 END AS `".$mvalue['Market']." -Number of Orders`, CASE WHEN `Market`='".$mvalue['Market']."' THEN SUM(`Records`) ELSE 0 END AS `".$mvalue['Market']." -Number of Order Line Items`,";
}
$createqry="CREATE TEMPORARY TABLE `temp_order_market` AS
SELECT ".$OrdersQry."`OrderDate` FROM
(SELECT COUNT(DISTINCT `OrderID`) AS `Count`,COUNT(`OrderID`) AS `Records`,`OrderDate`,`Market`
FROM `orders`
WHERE (`OrderDate` BETWEEN '$StartDate' AND '$EndDate')
GROUP BY `OrderDate`)
) AS `dummy` GROUP BY `OrderDate` ORDER BY `OrderDate` DESC";
echo $createqry."<br /><br />";
$resQry=mysql_query($createqry,$con) or die(mysql_error($con));
$selectqry="SELECT * FROM `temp_order_market`";
无论我得到什么结果都不准确。因为如果我得到个别市场的结果我得到了确切的结果。以下是我用于获取个别市场结果的查询。
SELECT SUM(`Count`) AS `Orders`,SUM(`Records`) AS `Records`,`OrderDate` FROM
(SELECT COUNT(DISTINCT `OrderID`) AS `Count`,COUNT(`OrderID`) AS `Records`,`OrderDate`
FROM `orders`
WHERE (`OrderDate` BETWEEN '2015-01-01' AND '2015-01-31') AND `Market`='$MarketName'
GROUP BY `OrderDate`)) AS `dummy` GROUP BY `OrderDate` ORDER BY `OrderDate` DESC";
现在我的问题是:
除了这个方法之外,我们可以这样做/这可以实现我正在使用的方法吗?
我怀疑我写过的查询的CASE声明。
请分享您的想法。提前谢谢。
答案 0 :(得分:0)
将SUM()添加到$ OrderQry,它现在正常工作。
$OrdersQry.="CASE WHEN `Market`='".$mvalue['Market']."' THEN SUM(`Count`) ELSE 0 END AS `".$mvalue['Market']." -Number of Orders`, CASE WHEN `Market`='".$mvalue['Market']."' THEN SUM(`Records`) ELSE 0 END AS `".$mvalue['Market']." -Number of Order Line Items`,";
$OrdersQry.="SUM(CASE WHEN `Market`='".$mvalue['Market']."' THEN SUM(`Count`) ELSE 0 END) AS `".$mvalue['Market']." -Number of Orders`, SUM(CASE WHEN `Market`='".$mvalue['Market']."' THEN SUM(`Records`) ELSE 0 END) AS `".$mvalue['Market']." -Number of Order Line Items`,";