sql-使用时间戳计算每周的记录数


sql - count records per weeks using timestamp

我有一个名为"tasaciones"的表,它有两列"record"answers"fecha"(fecha是时间戳)。

record  | fecha
-----------------------------
record1 | 2015-10-09 11:24:52
record1 | 2015-11-09 11:31:52
record2 | 2015-17-09 11:37:17
record3 | 2015-25-09 12:03:31
record3 | 2015-26-09 12:03:31
record4 | 2015-10-10 12:23:25
record4 | 2015-11-10 12:27:25

我需要通过从第一次记录之日到当前时间每周计数记录来进行周报。我发现了这样的东西,但即使这是我需要的,我也不知道如何将"while"写入echo数据。

SELECT year(fecha), datepart(week, fecha), count(*)
FROM tasaciones
GROUP BY year(fecha), datepart(week, fecha)

我想得到这样的结果:

第1周:15条记录

第2周:10条记录

第3周:25条记录

第4周:25条记录

MySQL中没有DATEPART()。。您可以改用YEARWEEK()。所以您的查询应该是这样的。

SELECT count(*) as numRecords, YEARWEEK(fecha) as weekNum
FROM table
GROUP BY YEARWEEK(fecha)

响应结果取决于您正在使用的api。

PDO:

$query = $SQL->prepare('...query here...');
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC))
{
    echo $row['tags'];
}

MYSQLI:

$qry = '...query here...';
$results = $mysqli->query($qry);
while($row = $results->fetch_assoc()){
    echo $row['numRecords'], $row['weekNum']
}

注意:我没有发布Mysql_api的方法来实现这一点,因为它已经被弃用,并且会导致sql注入以及许多其他问题。您应该切换到PDOMysqli_,如果您还没有

mysql中没有DATEPART,请尝试使用week。不要在计数中不必要地使用*,这会减慢sql的速度。

$query = "SELECT week(fecha) as w, count(record1) as cnt FROM tasaciones GROUP BY  week(fecha)";
    $res = $mysqli->query($query);
$table="<table><thead><th>WEEK</th><th>RECORDS</th></thead><tbody>";
    while ($results = $res->fetch_assoc()){
      $table .="<tr><td> Week:" . $results['w'] . "</td><td>" . $results['cnt'] . "records</td></tr>";
    }
 $table .="</tbody></table>";
echo $table;

关于问题的第一部分,您的查询应该如下所示:

SELECT year(fecha), datepart('week',fecha), count(*)
FROM tasaciones
GROUP BY year(fecha), datepart('week',fecha)
WHERE fecha <= timestamp(now())

关于你问题的第二部分(即"如何写'while'来回显数据"),我想你的意思是如何用PHP打印查询中的数据。所以,假设你使用PDO:

$query = "SELECT year(fecha), datepart('week',fecha), count(*) FROM tasaciones GROUP BY year(fecha), datepart('week',fecha) WHERE fecha <= timestamp(now())";
$sql = $db->query($sql);
while ($results = $result->fetch()){
  echo $results[0] . ' ' . $results[1] . ' : ' . $results[2] . 'records.<br />';
}

下面是问题的代码片段。

$sql = "SELECT year(fecha), datepart(week, fecha) as week, count(*) as week_total_record
FROM tasaciones
GROUP BY year(fecha), datepart(week, fecha)";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
   echo $row['week']." : ".$row['week_total_record'];
}