使用COUNT和ORDER BY和隐藏结果进行MySQL查询

时间:2019-05-18 14:53:15

标签: php mysql

我正在尝试获取正确的查询,在这里我可以按州显示每个州的数据,每个州的城市中都有商店(计数为每个城市的商店数)。任何帮助将不胜感激。

California
Los Angeles (5)
San Diego (8)
San Francisco (3)
...

现在,我的身分低于该数字,不会给我每个城市的数量。

$sql = "SELECT DISTINCT city, state FROM locations  WHERE open = 'Y' ORDER BY state ASC";
$result = mysqli_query($conn,$sql);
$num_columns = 1;
$rows = array();
while($row = mysqli_fetch_assoc($result)){
    if(!isset($rows[$row['state']])){
        $rows[$row['state']] = array();
    }
    $rows[$row['state']][] = $row['city'];
}
echo "<table>";
foreach($rows as $state => $cities){
    echo '<tr><th colspan="'. $num_columns .'">'. $state .'</th></tr>';
    $cityData = array_chunk ($cities, $num_columns); 
    sort($cityData);  // split array into chunk of $num_columns cities per array
    foreach($cityData as $row){
        echo "<tr>";
        for($i=0; $i<$num_columns; $i++){
            $city = isset($row[$i]) ? $row[$i] : "";
            echo "<td>$city</td>";
        }
        echo "</tr>";
    }
}
echo "</table>";

1 个答案:

答案 0 :(得分:2)

我可以建议以下GROUP BY查询:

SELECT
    city,
    state,
    COUNT(CASE WHEN open = 'Y' THEN 1 END) AS cnt
FROM locations
GROUP BY
    city,
    state
ORDER BY
    state;