计算日期范围内的天数总计

时间:2012-02-14 17:30:40

标签: php sql sum

我想计算任何给定(用户选择)日期范围,StartDate(sDate)到EndDate(eDate)的所有星期一,星期二等的总计。我当前的查询显示了范围内的所有日期,我希望每天都将我的表“计数”视为“计数”,但是将每周的每一天显示为一次。使用图像样本,我希望我的结果是: 星期一 - 164 星期二 - 139 星期三 - 261 等

SQL

SELECT areaname,created, SUM(count) as totals FROM reports WHERE created 
between '".$sDate."'  AND  '".$eDate."' AND area = '".$tArea."' GROUP BY areaname, 
created ORDER BY id ASC

HTML

foreach ($counts as $row) { ?>
<tr><td><?php echo date('l',strtotime($row['reports']['created'])); ?></td>
<?php echo $row[0]['totals']; ?>
}

sum of count for days within date range

1 个答案:

答案 0 :(得分:1)

您可以使用DATE_FORMAT()功能获取指定日期的星期几,然后您可以按此分组。语法为DATE_FORMAT(date, '%W')。所以:

SELECT areaname,
  DATE_FORMAT(created, '%W') AS weekday,
  SUM(count) AS totals
FROM reports
WHERE created BETWEEN '".$sDate."' AND '".$eDate."'
  AND area = '".$tArea."'
GROUP BY areaname, weekday
ORDER BY id

请注意,我已将areaname留在GROUP BY中,因此这将为areaname / weekday的每个组合返回一个结果。如果您想要所有areanames的总计,只需从GROUP BY子句中删除areaname