我随时间收集了一些帐户余额:
/**
* Reduces drag sensitivity of [ViewPager2] widget
*/
fun ViewPager2.reduceDragSensitivity() {
val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
recyclerViewField.isAccessible = true
val recyclerView = recyclerViewField.get(this) as RecyclerView
val touchSlopField = RecyclerView::class.java.getDeclaredField("mTouchSlop")
touchSlopField.isAccessible = true
val touchSlop = touchSlopField.get(recyclerView) as Int
touchSlopField.set(recyclerView, touchSlop*8) // "8" was obtained experimentally
}
每条记录均显示在指定时间戳记下客户的帐户总余额。帐户余额增加,例如当客户使用55充值时,从-35增至20。客户使用服务时,其帐户余额会减少,例如从5到-10。
我想用两种方式汇总这些数据:
1)获取每月和每年部门的借方,贷方和余额(贷方借方)。 4月的结果应该是以前所有月份的摘要:
+-----------------+------------+-------------+-----------------------+
| account_balance | department | customer_id | timestamp |
+-----------------+------------+-------------+-----------------------+
| 5 | A | 1 | 2019-02-12T00:00:00 |
| -10 | A | 1 | 2019-02-13T00:00:00 |
| -35 | A | 1 | 2019-02-14T00:00:00 |
| 20 | A | 1 | 2019-02-15T00:00:00 |
+-----------------+------------+-------------+-----------------------+
客户的帐户余额可能不会每月更改。 2月可能有客户1的帐户余额记录,但3月可能没有。
解决方案说明:
+---------+--------+-------+------------+-------+--------+
| balance | credit | debit | department | month | year |
+---------+--------+-------+------------+-------+--------+
| 5 | 10 | -5 | A | 1 | 2019 |
| 20 | 32 | -12 | A | 2 | 2019 |
| 35 | 52 | -17 | A | 3 | 2019 |
| 51 | 70 | -19 | A | 4 | 2019 |
+---------+--------+-------+------------+-------+--------+
EXTRACT(MONTH from timestamp) month
EXTRACT(YEAR from timestamp) year
2)按日期获取部门借方,贷方和余额的变化。
GROUP BY month, year, department
当我创建增量的总和时,我应该从1)中的结果中获取与最后一行相同的值。
解决方案说明:
+---------+--------+-------+------------+-------------+
| balance | credit | debit | department | date |
+---------+--------+-------+------------+-------------+
| 5 | 10 | -5 | A | 2019-01-15 |
| 15 | 22 | -7 | A | 2019-02-15 |
| 15 | 20 | -5 | A | 2019-03-15 |
| 16 | 18 | -2 | A | 2019-04-15 |
+---------+--------+-------+------------+-------------+
51 70 -19
计算增量答案 0 :(得分:1)
您的问题尚不清楚,但是听起来您想在任何给定的时间点获得未偿还的余额。
以下查询在1个时间点执行此操作。
with calendar as (
select cast('2019-06-01' as timestamp) as balance_calc_ts
),
most_recent_balance as (
select customer_id, balance_calc_ts,max(timestamp) as most_recent_balance_ts
from <table>
cross join calendar
where timestamp < balance_calc_ts -- or <=
group by 1,2
)
select t.customer_id, t.account_balance, mrb.balance_calc_ts
from <table> t
inner join most_recent_balance mrb on t.customer_id = mrb.customer_id and t.timestamp = mrb.balance_calc_ts
如果需要在一系列时间点进行计算,则需要修改日历CTE以返回更多日期。这就是BQ中CROSS JOINS的美丽!