1

我有一个列package并包含包 id 1, 2, 3, 4。现在我的查询将选择所有表stores_profile并按日期stores_fee过滤并按月分组

下面是我的数据库:

表:stores_profile

在此处输入图像描述

表:stores_fee

在此处输入图像描述

这是我当前的查询:

<?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>'; ?>

此代码的结果是:

在此处输入图像描述

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

在此处输入图像描述

4

2 回答 2

2

您可以尝试使用SUMand CASE

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)

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

于 2013-06-11T07:11:12.740 回答
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)
于 2013-06-11T07:11:04.440 回答