2017-01-02 53 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

非常感謝,它有幫助! –