PostgreSQL:明确获取相似ID的值之和

PostgreSQL: Getting sum of values of similar ids distinctly

我的数据库中有以下关系,

     id    |   month    | balance |
-----------+------------+---------+
 0009gmail | 2016-01-01 |    2000 |
 0009gmail | 2016-02-01 |    3500 |
 0009gmail | 2016-03-01 |     800 |
 0009gmail | 2016-04-01 |    1400 |
 0009gmail | 2016-05-01 |    -500 | 

问题是,我想要日期小于指定日期的不同 ID 的余额总和,

我正在使用此查询:

select distinct(id),sum(balance) from payment group by id,month having month<'2016-06-22';

但它给出了这个结果,

       id    |   sum 
-------------+---------
   0009gmail |    2000
   0009gmail |     800
   0009gmail |    1400
   0009gmail |    3500
   0009gmail |    -500

我认为我得到这个结果是因为将月份放在 group by 子句中,但是删除相同会给出一个错误,即月份必须在聚合函数的任一分组中,我想要这个输出,

     id    |   sum 
 ----------+---------
 0009gmail |    7200

请帮忙..

使用 id 的简单聚合:

SELECT id, SUM(balance) AS balance
FROM payment 
WHERE month<'2016-06-22'
GROUP BY id;

LiveDemo

图片来自:http://social.technet.microsoft.com/wiki/contents/articles/20724.all-at-once-operations-in-t-sql.aspx

  1. payement table
  2. 获取行
  3. 仅过滤满足month<'2016-06-22'
  4. 的那些
  5. GROUP BY id
  6. (HAVING)不需要

您正在寻找 where 子句:

select id, sum(balance)
from payment
where month < '2016-06-22'
group by id;

我觉得这种混乱很有趣。大多数人试图将 having 逻辑放在 where 子句中(where 子句中不允许使用聚合函数)。很少看到反方向的错误。

另请注意,select distinct 在聚合查询中几乎不适用。