2012-11-03 74 views
0

我有一个'用户订单'的表,其中有orderID,userID,orderStatus(可以是1,2,3)和orderTime。查询一段时间的订单百分比和订单数

我要计算过去150级的订单的百分比,在过去6一个月具有orderStatus 1.

我试图写的两个查询两个订单状态(1,2/3)用户ID = 1,然后计算订单的百分比,但我的查询不正确。

我的代码和查询:

$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; 

我怎样才能解决这个问题或改善我的代码。

+0

你想找到的百分比所有订单中的orderStatus = 1? – vinculis

+0

http://stackoverflow.com/questions/1576370/getting-a-percentage-from-mysql-with-a-group-by-condition-and-precision – ethrbunny

+0

@ethrbunny我检查这个Q和A,为答案它返回50个代理人的数字,但我想获得一个平均值为ordestatus的数字。 – Ali

回答

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;