MySql比使用Group By子句的数量小

时间:2018-01-08 11:06:15

标签: mysql sql

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

到目前为止,我有这个:

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

表示例:

| date_time           | quantity
-------------------------
| 2017-08-12 09:11:51 | 1
| 2017-08-12 10:12:51 | 1
| 2017-08-12 12:45:51 | 1
| 2017-08-13 11:12:51 | 1
| 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-14 | 2
| 2017-08-15 | 1
| 2017-08-16 | 1

我怎样才能实现这一目标?

1 个答案:

答案 0 :(得分:1)

尝试使用:您需要使用HAVING过滤群组,而WHERE过滤行

SELECT DATE(date_time) as date_time
    ,SUM(quantity) as quantity
FROM report
WHERE date_time BETWEEN '' AND  ''
GROUP BY DATE(date_time)
HAVING SUM(quantity) < 3  --Before it was data specific COUNT(quantity)