MySQL列中的值计数

时间:2013-06-11 07:04:38

标签: php mysql

我有一个列package并包含包ID 1, 2, 3, 4。现在,我的查询将选择所有表stores_profilestores_fee并按日期过滤,并按

分组

以下是我的数据库:

表:stores_profile

enter image description here

表:stores_fee

enter image description here

这是我当前的查询:

<?php
$filter_date = '2013-04-01';

$result = mysql_query("SELECT sp.*, sf.*, sp.id as store_profile_id,DATE_FORMAT(sf.date_start, '%d-%m-%Y') as month
 FROM `stores_profile` sp
 left join `stores_fee` sf ON sp.id=sf.store_id 
 where sf.date_start >= '".$filter_date."' GROUP BY MONTH(sf.date_start) ");

while($row = mysql_fetch_array($result)) {
    $month = date('M', strtotime($row['month']));
    $package = $row['package']; 
?>
      <tr>
        <td><?php echo $month ?>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
        <td>&nbsp;</td>
      </tr>
<?php } echo '</table>'; ?>

此代码的结果是:

enter image description here

那么,如何计算列package中的包ID然后按月分组并根据包ID得到总数,我知道它有点令人困惑,但结果应如下所示:

enter image description here

2 个答案:

答案 0 :(得分:2)

您可以尝试使用SUMCASE

SELECT DATE_FORMAT(sf.date_start, '%d-%m-%Y') as `Month`,
       SUM(CASE WHEN sf.package = 1 THEN 1 ELSE 0 END) AS `Package 1`,
       SUM(CASE WHEN sf.package = 2 THEN 1 ELSE 0 END) AS `Package 2`,
       SUM(CASE WHEN sf.package = 3 THEN 1 ELSE 0 END) AS `Package 3`,
       SUM(CASE WHEN sf.package = 4 THEN 1 ELSE 0 END) AS `Package 4`
FROM `stores_profile` sp
LEFT JOIN `stores_fee` sf ON sp.id = sf.store_id 
WHERE sf.date_start >= '".$filter_date."' GROUP BY MONTH(sf.date_start)

我能想到的另一种方法是对它进行子查询。

答案 1 :(得分:1)

如果我理解了您的要求,您需要一个支点:

SELECT 
    SUM(IF(sf.package=1,1,0)) as package_1,
    SUM(IF(sf.package=2,1,0)) as package_2,
    SUM(IF(sf.package=3,1,0)) as package_3,
    SUM(IF(sf.package=4,1,0)) as package_4,
    DATE_FORMAT(sf.date_start, '%d-%m-%Y') as `month`
 FROM 
    `stores_profile` sp
 LEFT JOIN  `stores_fee` sf 
    ON sp.id=sf.store_id 
 WHERE 
    sf.date_start >= '".$filter_date."' 
 GROUP BY 
    MONTH(sf.date_start)