我的表就像这样
# group rows based on cumsum with reset
cumsum_with_reset_group <- function(x, threshold) {
cumsum <- 0
group <- 1
result <- numeric()
for (i in 1:length(x)) {
cumsum <- cumsum + x[i]
if (cumsum > threshold) {
group <- group + 1
cumsum <- x[i]
}
result = c(result, group)
}
return (result)
}
# cumsum with reset
cumsum_with_reset <- function(x, threshold) {
cumsum <- 0
group <- 1
result <- numeric()
for (i in 1:length(x)) {
cumsum <- cumsum + x[i]
if (cumsum > threshold) {
group <- group + 1
cumsum <- x[i]
}
result = c(result, cumsum)
}
return (result)
}
# use functions above as window functions inside mutate statement
df %>% group_by() %>%
mutate(
cumsum_10 = cumsum_with_reset(value, 10),
group_10 = cumsum_with_reset_group(value, 10)
) %>%
ungroup()
我想这样显示(通过添加行)
S.No. Name Amount
1 Mike 200
2 Jason 150
3 Mike 100
4 Andy 300
5 Jason 200
我的代码是 -
S.No. Name Amount
1 Mike 300
2 Jason 350
3 Andy 300
如果使用Ruby on Rails名称字段相同,如何添加金额?
答案 0 :(得分:1)
使用架构,数据和&amp ;;编辑答案码。
这是表格架构&amp;记录
mysql> select * from users;
+----+-----------+------------+------------+
| id | full_name | created_at | updated_at |
+----+-----------+------------+------------+
| 1 | Gowtham | NULL | NULL |
| 2 | Mike | NULL | NULL |
| 3 | Jason | NULL | NULL |
| 4 | Andy | NULL | NULL |
+----+-----------+------------+------------+
mysql> select * from data;
+----+--------------+------------+--------+------------+------------+
| id | from_user_id | to_user_id | amount | created_at | updated_at |
+----+--------------+------------+--------+------------+------------+
| 1 | 1 | 2 | 200 | NULL | NULL |
| 2 | 1 | 2 | 100 | NULL | NULL |
| 3 | 1 | 2 | 150 | NULL | NULL |
| 4 | 1 | 2 | 200 | NULL | NULL |
| 5 | 1 | 3 | 150 | NULL | NULL |
| 6 | 1 | 3 | 200 | NULL | NULL |
| 7 | 1 | 4 | 300 | NULL | NULL |
+----+--------------+------------+--------+------------+------------+
现在,这里是一个代码,用于查找Gowtham向其他人完成的所有转移。你可以将它放在你的控制器中
@result = Data.where(:from_user_id => 1).select("users.full_name, SUM(data.amount) as total").joins("INNER JOIN users ON users.id = data.to_user_id").group(:to_user_id)
您可以遍历@result并在视图中显示
<table class="table">
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<% @result.each_with_index do |tc, index| %>
<% begin %>
<tr>
<td><%=index+1%></td>
<td><%=tc.full_name%></td>
<td><%=tc.total%></td>
</tr>
<% rescue %>
<% next %>
<% end %>
<% end %>
</tbody>
</table>
希望这有帮助
答案 1 :(得分:1)
您可以尝试使用此功能获取名称及其总金额
Data.select("name, sum(amount) as amount").group(:name)