2017-01-02 55 views
1

我有表差分具有相同值的

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

我需要找到用户ID 123项的总和和出局上日期2016-08-01',还有balans,这些都应该算作userid123的全部数字。 我使用查询

select distinct userid, type, sum(amount) 
from fct_bonus 
where userid = 123 and date <= '2016-08-01' 
group by type 

,但我不知道,怎么算的balans。请帮忙。

+1

编辑你的问题,(1)提供的样本数据; (2)期望的结果;和(3)标记您正在使用的数据库。 –

回答

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; 
+0

非常感谢,它有帮助! –