求子查询结果

时间:2018-01-10 07:51:04

标签: mysql sql

表示例:

| 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

我可以使用此查询获得结果

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 

结果

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

之后我想要数量。例如:

 quantity
---------
| 4

为了达到这个目的,我知道我需要使用结果作为子查询来进行总结。我试过这个但是错了:

SELECT SUM(topla) FROM (
  ( 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 
  ) AS topla
)

如何量化数量?

2 个答案:

答案 0 :(得分:1)

只需将数量替换为topla并删除&#39; as topla&#39;来自topla。之前的查询。

SELECT SUM(quantity) total FROM (
  ( SELECT DATE(date_time) as date_time
        ,SUM(quantity) as quantity
    FROM report
    WHERE date_time BETWEEN '' AND  ''
    GROUP BY DATE(date_time)
    HAVING total < 3 
  )
)

要使用SUM函数,您必须提供列名而不是表名。

答案 1 :(得分:1)

首先,您必须按列名称对数量求和。 (在我将其命名为sub_quantity的示例中)

其次,您无需选择日期。

所以你的查询可能是

SELECT SUM(sub_quantity) AS quantity
FROM
  ( SELECT SUM(quantity) AS sub_quantity
   FROM report
   WHERE date_time BETWEEN '' AND ''
   GROUP BY DATE(date_time)
   HAVING SUM(quantity) < 3) a