我正试图从我的数据库中获得不同的成本,以及该不同成本的计数。我得到的是'独特的成本'回来,但不是'成本'我将需要运行我的下一个进程。有人能帮我把单独的费用和伯爵一起还给我吗?

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

最佳答案

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

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

关于php - 选择一个不同的值计数及其值为自身的1查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27916924/

10-13 05:32