如果不存在则查询返回零

时间:2015-02-22 22:38:39

标签: sql sql-server-2008 join

我有一张包含货币,付款方式和invoiceamount的表格。我必须编写查询来获取货币,付款方式和总发票金额。使用group by非常简单。但实际上我有三种支付类型0,1,2,表中的数据是

Currency.  Paymenttype invoice amount
Aaa.        0.           100
Aaa.        1.           200
Aaa.        1.            50
Bbb.        0.           150
Bbb.        1.           100
Bbb.        2.           100

我的查询是选择货币,paymenttype,sum(invoiceamount)作为表group by货币的总额,paymenttype

结果

  Currency  paymenttype total
  Aaa.       0.           100
  Aaa.       1.           250
   Bbb.      0.           150
   Bbb.      1.           100
   Bbb.      2.           100

但我想要的是Aaa。没有2个paymenttype也应该显示一个0值的行,如下所示。

     Aaa.     2.     0

怎么做?

2 个答案:

答案 0 :(得分:0)

您可以使用cross join生成所有行,然后加入您想要的数据:

select c.currency, pt.paymenttype,
       coalesce(sum(i.invoiceamount), 0) as total
from currency c cross join
     paymenttype pt left join
     invoice i
     on i.currency = c.currency and i.paymenttype = pt.paymenttype
group by c.currency, pt.paymenttype;

答案 1 :(得分:0)

你应该有一个包含所有类型的表。

然后你只需在payment_type_id上​​输入一个left join输出总数,如果没有则输出0。

如果你没有包含所有类型的表,那么你可以模拟它,但这将是一个肮脏的修复:

select a.currency, b.paymenttype, coalesce(sum(a.invoiceamount), 0)
from (select 0 as paymenttype,
      union all select 1 as paymenttype,
      union all select 2 as paymenttype) b
left join yourTable a on a.paymenttype = b.paymenttype
group by a.currency, b.paymenttype;
相关问题