2012-10-06 36 views
1

这是一个通用的SQL问题,但我使用了Firebird。SUM和SUM在同一个表中的SQL请求

我有这个表(简体):

 
id amount type idtype 
-------------------- 
1 10  in1 0 
2 15  in2 0 
3 5  out1 1 
4 4  out2 1 
5 5  out3 2 

idtype栏“显示”来袭部分的ID,并补充:我不能用我问的形式“类型”一栏,“事业型每次都是不一样的。 idtype传入具有“0”,这意味着“进入部分”

所以,我想有结果:

 
id in  out 
-------------------- 
1 10  9  
2 15  5 

我已经试过这样:

 
select 
    id, 
    amount, 
    (
    select 
     SUM (amount) as together 
    from 
     mytable 
    where 
     idtype 0 
    group by 
     id 
    ) as "out" 
from 
    mytable 
where 
    idtype = 0 

但这不起作用。 有什么建议吗?

回答

1

在条件中,您正在使用id字段而不是idtype,并且您不符合您想归纳为任何内容的记录。

select 
    id, 
    amount, 
    (
    select 
     SUM (amount) as together 
    from 
     mytable 
    where 
     idtype = t.id 
    ) as "out" 
from 
    mytable t 
where 
    idtype = 0 

你也可以把它写成一个连接:

select 
    id, 
    amount, 
    sum(t2.amount) as "out" 
from 
    mytable t 
    innerjoin mytable t2 on t2.idtype = t.id 
group by 
    t.id, t.amount 
where 
    idtype = 0 
+0

谢谢,赖特和快速的答案! – user1724995