2012-02-14 261 views
2

我想計算任何給定(用戶選定)日期範圍,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

你可以使用DATE_FORMAT()函數來獲得th從某個特定日期開始的一週中的某一天,然後您可以將其分組。語法是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

+0

完美。那很棒。謝謝! – sloga 2012-02-14 18:10:51