使用MySql查询计算低,中,平均,高

时间:2014-09-03 05:37:18

标签: php mysql

我的表中有以下记录:

  Name            Status          Price

Product 1         Active           110
Product 2         Active           165
Product 3         Expire           256
Product 4         Pending          154
Product 5         Active           856
Product 6         Expire           523
Product 7         Pending          220
Product 8         Active           321
Product 9         Pending          478
Product 10        Expire           210

我需要通过mysql查询输出如下:

 Status       Low         Median          Average         High

 Active        ?            ?               ?              ?
 Expire        ?            ?               ?              ?
 Pending       ?            ?               ?              ?

我不知道如何通过mysql查询来做到这一点。

提前致谢。

3 个答案:

答案 0 :(得分:3)

SELECT status, MIN(price) as Low, MAX(price) as High, AVG(price) as Average 
FROM  your_table
GROUP BY status

答案 1 :(得分:1)

尝试以下代码:

<?php

    $arr = array( 'Active', 'Expire', 'Pending');

    foreach($arr as $status) {

        $stmt = "SELECT a.max, a.min, a.avg, price AS med, IF(price > a.avg, price - a.avg, a.avg-price ) AS diff FROM tbl_report_address_lists, ( SELECT ROUND(AVG(price),2) as avg, MAX(price) AS max, MIN(price) AS min FROM tbl_report_address_lists WHERE `report_id` = 13 AND `status` = '$status') AS a WHERE `report_id` = 13 AND `sales_code` = '$status' ORDER BY diff ASC LIMIT 1";

        // execute query, get result data and use it    
    }

?>

答案 2 :(得分:0)

我准备了以下查询来计算High,Low,Med和Avg,但此查询仅计算单个状态的价格:

SELECT STATUS , a.max AS High, a.min AS Low, a.avg AS Avg, Price AS Med, IF( Price > a.avg, Price - a.avg, a.avg - Price ) AS diff
FROM Table, (
  SELECT ROUND( AVG( Price ) , 2 ) AS avg, MAX( Price ) AS max, MIN( Price ) AS min
  FROM Table
  WHERE STATUS =  'Pending'
) AS a
WHERE STATUS =  'Pending'
ORDER BY diff ASC 
LIMIT 1

如果我删除了WHERE STATUS =&#39;等待&#39;条件,返回不准确的结果。