Sql 如果不存在,则查询返回零
我有一张有货币、付款类型和发票金额的桌子。我必须编写查询以获取货币、paymenttype和总发票金额。这是非常简单的分组方式。但实际上我有三种付款类型0、1、2,表中的数据是Sql 如果不存在,则查询返回零,sql,sql-server-2008,join,Sql,Sql Server 2008,Join,我有一张有货币、付款类型和发票金额的桌子。我必须编写查询以获取货币、paymenttype和总发票金额。这是非常简单的分组方式。但实际上我有三种付款类型0、1、2,表中的数据是 Currency. Paymenttype invoice amount Aaa. 0. 100 Aaa. 1. 200 Aaa. 1. 50 Bbb. 0. 150 Bbb.
Currency. Paymenttype invoice amount
Aaa. 0. 100
Aaa. 1. 200
Aaa. 1. 50
Bbb. 0. 150
Bbb. 1. 100
Bbb. 2. 100
我的查询是按货币、paymenttype从表组中选择货币、paymenttype、suminvoiceamount作为总计
结果
Currency paymenttype total
Aaa. 0. 100
Aaa. 1. 250
Bbb. 0. 150
Bbb. 1. 100
Bbb. 2. 100
但我想要的是Aaa级。没有2个paymenttype is也应该显示一个值为0的行,如下所示
Aaa. 2. 0
如何执行此操作?您可以使用交叉联接生成所有行,然后联接所需的数据:
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;
您应该有一个包含所有类型的表 然后,您只需在payment\u type\u id上执行左连接,输出总数,如果没有,则为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;
这对我的数据不起作用。虽然我的查询是select aa.Currency,aa.PaymentType,sumbb.amount from select*from select distinct PaymentType from payment交叉连接选择distinct Currency from payment c aa left join payment bb on aa.PaymentType=bb.PaymentType和aa.Currency=bb.Currency group by aa.PaymentType,aa.Currency订单by aa.Currency