Select 一个不同的值计数及其自身的值 1 查询

Select a distinct value count and the value it's self 1 query

我正在尝试从我的数据库中接收不同的成本,以及该不同成本的计数。我得到了 'DISTINCT COST' 但没有 'COST' 我将需要 运行 我的下一个过程。有人可以帮我 return 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";
                 }

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

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