2个选择语句中的2个不同表的求和函数。怎么了?

时间:2014-09-07 12:47:24

标签: sql

`我有2个表:收入和销售额,我想在查询中显示:

a)收入总和
b)销售总额
c)现在的产品数量 - a-b之间的差异

表'收入'有字段:Incomeid,ProductId,quant等 表'sales'包含字段:SalesId,IncomeId,ProductId,quant等。

我的SQL是:

select i.productId, sum(i.quant) as iq, sum(s.quant) as sq    
from income i,sales s  
where (i.incomeId=s.incomeId)  
group by i.productId

select i.productId, sum(i.quant) as iq, sum(s.quant) as sq  
from income  
left outer join  s on  (i.IncomeId=s.IncomeId)  
group by i.productId

我的目标是如下结果:

现在的总和(收入)总和(销售额)

1 200 50 150
   2 150 20 130
   3 120 100 20

但我得错了(收入):
Id sum(收入)总和(销售额)现在

1 20000 50 19950
 2 27500 20 27480
 3 125000 100 12400

如何编写SQL查询以获取此信息?

有关信息,我的数据库服务器是Interbase 2009。 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我会用:

select incomecode,
       sum(case when which = 'income' then sum_amt else 0 end) as sum_income,
       sum(case when which = 'sales' then sum_amt else 0 end) as sum_sales,
       sum(case when which = 'income' then sum_amt else 0 end)
     - sum(case when which = 'sales' then sum_amt else 0 end) as diff_between
  from (select incomecode, sum(quant) as sum_amt, 'income' as which
          from income
         group by incomecode
        union all
        select incomecode, sum(quant), 'sales'
          from sales
         group by incomecode) x
group by incomecode

Interbase似乎不支持内联视图,并且在您的版本中,还不支持case语句。在这种情况下,请尝试以下方法:

步骤1:创建收入总额视图

create view income_vw
select incomecode, sum(quant) as sum_amt
  from income
 group by incomecode

第2步:为销售总额创建视图

create view sales_vw
select incomecode, sum(quant) as sum_amt
  from sales
 group by incomecode

步骤3:运行最终选择查询,该查询将使用这两个视图

select coalesce(i.incomecode, s.incomecode) as incomecode,
       coalesce(i.sum_amt, 0) as sum_income,
       coalesce(s.sum_amt, 0) as sum_sales,
       coalesce(i.sum_amt, 0) - coalesce(s.sum_amt, 0) as diff_between
  from income_vw i
  full outer join sales_vw s
    on i.incomecode = s.incomecode