我有桌子
create table fct_bonus (
date timestamp not null,
type varchar(10) not null,
amount numeric(19,2) not null,
userid varchar(30) not null
)
类型可以是IN或OUT,金额始终> 0
我需要在2016-08-01日期找到用户ID 123的来龙去脉,以及balans,这应该算作所有ins减去userid123的所有输出。 我使用查询
select distinct userid, type, sum(amount)
from fct_bonus
where userid = 123 and date <= '2016-08-01'
group by type
但我不知道,如何计算balans。请帮忙。
答案 0 :(得分:3)
这似乎就是你所描述的:
select userid,
sum(case when type = 'IN' then 1 else 0 end) as ins,
sum(case when type = 'OUT' then 1 else 0 end) as outs,
sum(case when type = 'IN' then amount when type = 'OUT' then - amount end) as balance
from fct_bonus
where userid = 123 and date <= '2016-08-01'
group by userid;