2012-11-03 111 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;