如果条件为真,则在使用两个不同的语句时使用CASE语句

时间:2015-06-17 07:33:46

标签: php mysql

  1. 我需要显示从表Market中检索的数据。对于每个市场,可以计算和显示订单数量和项目数量。我只有一栏即市场,但我需要横向展示市场。
  2. 我尝试过创建临时表来实现这一目标。无论如何我得到了结果,但不准确。

        $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`";
    
    1. 无论我得到什么结果都不准确。因为如果我得到个别市场的结果我得到了确切的结果。以下是我用于获取个别市场结果的查询。

      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";
      
    2. 现在我的问题是:

      1. 除了这个方法之外,我们可以这样做/这可以实现我正在使用的方法吗?

      2. 我怀疑我写过的查询的CASE声明。

      3. 请分享您的想法。提前谢谢。

1 个答案:

答案 0 :(得分:0)

将SUM()添加到$ OrderQry,它现在正常工作。

OLD

$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`,";