Sql查询sum(字段)与另一个字段和限制的顺序

时间:2018-01-18 13:14:58

标签: mysql sql-server postgresql

我的下表名称为“banking”

+------------------------------+
|    id | amount | created     |
+------------------------------+
| 1 | 10 | 2018-01-18 00:10:00 |
| 2 | 20 | 2018-01-18 00:50:00 |
| 3 | 30 | 2018-01-18 00:20:00 |
| 4 | 40 | 2018-01-18 00:30:00 |
+------------------------------+

我需要输出为60

我试过这个查询

SELECT sum(amount) 
  FROM banking 
 WHERE created >= '2018-01-18 00:00:00' 
   AND created < '2018-01-18 18:01:35' 
 GROUP 
    BY created
 ORDER 
    BY created DESC LIMIT 2;

但是我得到了一个输出

+---------+
|   | sum |
+---------+
| 1 | 20  |
| 2 | 40  |
+---------+

如何将单标量输出设为60(40 + 20之和)

1 个答案:

答案 0 :(得分:-1)

这应该足够了:

select sum(amount) from
(SELECT sum(amount) amount FROM banking 
WHERE created >= '2018-01-18 00:00:00' AND created < '2018-01-18 18:01:35' 
GROUP BY created ORDER BY created DESC LIMIT 2)sum_amount;

检查 SQL Fiddle