sql - 仅对具有多行的组求和值

标签 sql postgresql aggregate having

我有这个问题:

SELECT extract(year from date1), extract(month from date1), spending    
FROM ( SELECT *, COUNT(*) OVER(PARTITION BY CONCAT(extract(year FROM date1), extract(month FROM date1))) N
       FROM table) as A    
WHERE N > 1    
GROUP BY date1    
ORDER BY date1 ASC;

结果是:

enter image description here

仅当有不止一行包含 equla yearmonth 时,我才需要对字段 spending 求和。期望的结果:

year    month   spending
----    -----   --------
2015     1        5424
2016     1      605886
2016     5      xxxxxx
....     ..     ......

最佳答案

好的,我找到了解决方案:拥有:

SELECT extract(year from date1), extract(month from date1), spending    
FROM table  
GROUP BY extract(month from date1)), extract(year from date1), extract(month from date1)
HAVING count (CONCAT(extract(year from date1), extract(month from date1))) > 1
ORDER BY extract(year from date1), extract(month from date1) ASC; 

以防对某人有帮助。

关于sql - 仅对具有多行的组求和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47791862/

相关文章:

php - 如果插入另一个表中的值,如何更新表

JavaFX 登录隐藏按钮

sql - 分组依据中的最大行数

javascript - 如何防止 Knex 在 PostgreSQL 上插入尾随空格?

c# - MYSQL 插入...重复值再次插入增量

sql - 将 SQL 调优向导与 sp_prepexec 语句结合使用

Postgresql 函数返回受影响的行数

c - C中的标量类型和聚合类型有什么区别?

eclipse - P2 存储库聚合器

postgresql - 合并postgres中的字段聚合