作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个具有这种结构的表:
id | name | batch_id | used
----------------------------------
1 | voucher 1 | 1 | 1
2 | voucher 2 | 1 | 0
3 | voucher 3 | 1 | 1
4 | voucher 4 | 2 | 0
5 | voucher 5 | 3 | 1
我需要运行一个查询,该查询将按 batch_id 分组并对使用的列求和。
所以我需要的结果是:
batch_id | sum_used
----------------------------------
1 | 2
2 | 0
3 | 1
这是我目前所拥有的:
TableName.select('DISTINCT ON (batch_id) batch_id')
这与:
SELECT DISTINCT ON (batch_id) batch_id FROM table_name
分组有效,但我无法求和。
谁能指出我正确的方向?
最佳答案
需要使用GROUP BY
和SUM
聚合函数:
SELECT batch_id, SUM(used::int) AS sum_used
FROM table_name
GROUP BY batch_id
ORDER BY batch_id;
输出:
╔═══════════╦══════════╗
║ batch_id ║ sum_used ║
╠═══════════╬══════════╣
║ 1 ║ 2 ║
║ 2 ║ 0 ║
║ 3 ║ 1 ║
╚═══════════╩══════════╝
或者使用窗口函数:
SELECT DISTINCT batch_id, SUM(used::int) OVER(PARTITION BY batch_id) AS sum_used
FROM table_name
ORDER BY batch_id
关于ruby-on-rails - rails + PostgreSQL : grouping together with a sum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34652473/
我是一名优秀的程序员,十分优秀!