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

时间:2015-10-29 16:54:32

标签: php mysql sql

我有一个名为'tasaciones'的表,它有2列'记录'和'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条记录

4 个答案:

答案 0 :(得分:3)

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注入以及许多其他问题。如果您还没有

,请切换到 PDO Mysqli _

答案 1 :(得分:1)

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;

答案 2 :(得分:-1)

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

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

关于你问题的第二部分(即“如何写''以回显数据'),我想你的意思是如何在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 />';
}

答案 3 :(得分:-1)

以下是您问题的代码段。

$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'];
}
相关问题