0

我有一个“用户订单”表,其中包含 orderID、userID、orderStatus(可以是 1、2、3)和 orderTime。

我想计算最后 150 个订单的百分比,在过去 6 个月中,用户 ID = 1,其 orderStatus 为 1。

我尝试为两个订单状态(1、2/3)编写两个查询,然后计算订单百分比,但我的查询不正确。

我的代码和查询:

$rs1 = mysql_query("select count(*) as orderCount1 from userorders where 
         orderStatus = 1 and orderID in (select top 150 orderID from userorders where 
          userid = 1 and orderStatus in (1,2,3)  and  
         orderTime > ".strtotime("-6 month")." oder by orderID desc)") or  
         die (mysql_error());

$rs2 = mysql_query("select count(*) as orderCount1 from userorders where 
         orderStatus in (2,3) and orderID in (select top 150 orderID from userorders where 
          userid = 1 and orderStatus in (1,2,3)  and  
         orderTime > ".strtotime("-6 month")." order by orderID desc)") or  
         die (mysql_error());


$orderCount1 = $rs1['orderCount1'];
$orderCount2 = $rs2['orderCount2'];

$orderPercent = ($orderCount1/ $orderCount1+$orderCount2)*100;

我该如何解决问题或改进我的代码。

4

1 回答 1

0

我找到了正确的查询。

它有一个具有最多条件的主查询,订单百分比是根据主查询的输出计算得出的:

$rs = mysql_query("select (sum(case when orderStatus = 1 then 1 else 0 end) 
         /count(orderStatus))*100 as percentage from (select orderStatus from  
         userorders where orderStatus in (1,2,3) and userid = 1 and  
         orderTime > ".strtotime("-6 month")."  order by orderID desc limit 
          150) tempTable") or die (mysql_error());

$percentage1 = $rs['percentage'];

对于 orderStaus 2,3

$percentage2 = 100 - $percentage1;
于 2012-11-03T22:14:15.283 回答