选择一个不同的值计数及其自我1查询的值

时间:2015-01-13 07:28:04

标签: php mysql sql select

我正在尝试从我的数据库中获得不同的成本,也是这个不同成本的计数。我正在获得' DISTINCT COST'回来但不是' COST'我需要运行我的下一个过程。有人可以帮我回复DISTINCT COST本身以及计数吗?

 $sql="SELECT COUNT(DISTINCT COST) AS COSTQ FROM STATS WHERE PURCHASEID = ".$purchaseid;
       $result = $mysqli->query($sql);

        if ($result->num_rows > 0) {
            // output data of each row
            while($row = $result->fetch_assoc()) {
                $costcoun = $row['COSTQ'];
                $cost = $row['COST']; // I have already tried ['DISTINCT COST'] which i had no luck with either.
              // This is where I run my next process
                  }
                 } else {
                      echo "0 results";
                 }

1 个答案:

答案 0 :(得分:3)

group by子句是针对这种情况设计的 - 它将查询分解为不同的值,并分别对每个组应用聚合函数:

SELECT   cost, 
         COUNT(*) AS costq -- No need for distinct, GROUP BY handles it
FROM     stats
WHERE    purchaseid = 'something'
GROUP BY cost