如何从mysql获取数据并在几周内将它们分组,也按月分开

时间:2011-12-08 11:50:23

标签: mysql

我有mysql数据库,并且有超过2年的数据。如何以一种得到如下结果的方式进行查询?:

January
   Week 1
      ...
      data rows here
      ....
   Week 2
      ...
      ...
   Week 3
      ...
      ...
   Week 4
      ...
      ...

February (same as above)

这些是字段结构:

- date (in yyyy-mm-dd format)
- job (integer autoincrement)
- person (varchar)

4 个答案:

答案 0 :(得分:5)

试试这个,它会产生非常类似于你所需要的输出

SELECT MONTH(date) AS MONTH, WEEK(date) AS WEEK, DATE_FORMAT(date, %Y-%m-%d) AS DATE, job AS JOB, person AS PERSON GROUP BY WEEK(date);

答案 1 :(得分:2)

 GROUP BY year(record_date), MONTH(record_date)

查看MySQL中的date and time functions

答案 2 :(得分:2)

它必须是查询,或者你也可以使用ajax?使用ajax你可以在javascript中执行循环:

date = [initial date]
while date <= [final date] {
    divUpdate = 'divrecs'; // will be used in updateDiv function
    url = 'getrecs.php?date1='+date+'&date2='+(date+6);
    conecta(url,updateDiv);
    date = date+7;
}

在getrecs中你的查询将是:

$stmt = $dbh->prepare("select * from yourtable where date >= '".$_GET['date1']."' and date <= '".$_GET['date2']."'");
if ($stmt->execute()) {
    while ($row = $stmt->fetch(PDO::FETCH_BOTH)) {
        echo "Do anything with your data here: $row[1] etc<BR>";
    }
}

希望有所帮助!

答案 3 :(得分:0)

SELECT MONTH(created_datetime) AS month, WEEK(created_datetime) AS week, DATE(created_datetime) AS date, COUNT(id) AS count FROM users WHERE date(created_datetime) BETWEEN '2017-05-01' AND '2017-12-31' GROUP BY month ORDER BY created_datetime

如果您希望日期记录,则需要使用GROUP BY日期 如果您希望每周记录一次,则需要使用GROUP BY周 如果您想要每月记录,则需要使用GROUP BY月。