MySql GROUP BY date_time和SUM数量

时间:2017-08-16 15:09:02

标签: mysql sql node.js

在报表中,每天都有多个 date_time 数量记录。我想分别为每天的记录选择数量总和。

       connection.query("SELECT  date_time, quantity FROM report WHERE date_time BETWEEN ? AND  ?", [fromDate_query, toDate_query], function(err, rows) {
              if (err) console.log(err);
              else {
                for (var i = 0; i < rows.length; i++) {
                  var row = rows[i];
                  console.log("**********************************");
                  console.log("date_time : " + row.date_time);
                  console.log("quantity : " + row.quantity);
                  console.log("**********************************");
                }
                io.emit("chart", rows);
              }
              // console.log(rows);
            });

表示例

| date_time           | quantity
-------------------------
| 2017-08-13 11:12:51 | 1
| 2017-08-13 12:45:51 | 1
| 2017-08-13 13:57:51 | 1
| 2017-08-14 14:23:51 | 1
| 2017-08-14 16:34:51 | 1
| 2017-08-15 16:21:51 | 1
| 2017-08-16 14:31:51 | 1

选择后

| date_time  | quantity
 -------------
| 2017-08-13 | 3
| 2017-08-14 | 2
| 2017-08-15 | 1
| 2017-08-16 | 1

如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

将时间戳转换为日期并GROUP BY日期,最后SUM将数量转换为COUNT(quantity)

  SELECT DATE(date_time)
        ,SUM(quantity) 
    FROM report
   WHERE date_time BETWEEN ? AND  ?
GROUP BY DATE(date_time)