我有一个'userorders'表,它有orderID,userID,orderStatus(可以是1,2,3)和orderTime。
我想计算最近150个订单的百分比,在过去6个月中,userid = 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;
如何解决问题或改进我的代码。
答案 0 :(得分: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'];
for orderStaus 2,3
$percentage2 = 100 - $percentage1;