简体   繁体   English

查询一段时间内的订单百分比和订单数量

[英]Query for percent of orders for a period of time and number of orders

I've got a table of 'userorders' which have orderID, userID , orderStatus (which can be 1,2,3) and orderTime. 我有一张“用户订单”表,其中有orderID,userID,orderStatus(可以是1,2,3)和orderTime。

I want to calculate percent of last 150 orders, in last 6 month for userid = 1 which has orderStatus 1. 我想计算最近6个月内的userid = 1(具有orderStatus 1)的最近150个订单的百分比。

I tried to write two queries for both orders Status (1, 2/3) and then calculate percent of orders but my queries are not correct. 我尝试为两个订单状态(1、2 / 3)编写两个查询,然后计算订单百分比,但查询不正确。

my code and queries: 我的代码和查询:

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

How can I solve the problem or improve my codes. 如何解决该问题或改进我的代码。

I find out the right query. 我找到正确的查询。

It has one main query which has most conditions and the percent of order is calculated from output of main query : 它具有一个条件最多的主查询,并且订单百分比是根据主查询的输出计算得出的:

$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 订购Staus 2,3

$percentage2 = 100 - $percentage1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM