如果不存在则查询返回零

1 join sql-server

我有一个表currencypaymenttypeinvoiceamount。我必须写一个查询来获取currencypaymenttypeinvoiceamount完成。

这对于 group by 来说非常简单。但实际上我有3种支付类型——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
Run Code Online (Sandbox Code Playgroud)

我的查询是

Select currency, paymenttype, sum(invoiceamount) as total
from table 
group by currency, paymenttype
Run Code Online (Sandbox Code Playgroud)

结果

      Currency  paymenttype total
      Aaa.       0.          100
      Aaa.       1.          250
      Bbb.       0.          150
      Bbb.       1.          100
      Bbb.       2.          100
Run Code Online (Sandbox Code Playgroud)

作为Aaa。没有paymenttype2 它也应该显示一个值为 0 的行,如下所示。

      Aaa.      2.     0
Run Code Online (Sandbox Code Playgroud)

这该怎么做?

Phi*_*lᵀᴹ 7

如果付款类型和货币列表已知,您可以使用 CTE 执行此操作。

with paymenttypes as (
  select 0 as ptype,
  Union select 1 as ptype,
  Union select 2 as ptype ), 
currencies as 
( select 'Aaa' as currency
  union
  select 'Bbb' as currency ),
sourcedata as (
  select currency, ptype as paymenttype, 0 as amount
  from currencies, paymenttypes
  Union all
  select * 
  from data)
select currency, paymenttype, sum(amount)
from sourcedata
group by currency, paymenttype;
Run Code Online (Sandbox Code Playgroud)

它基本上创建了所有货币的笛卡尔积,paymenttype 对的金额为 0,然后将其与源数据连接起来。

如果您的付款类型和货币列表都在查找表中,请将其替换。

另请注意,还有其他方法,使用COALESCE等。

SQL小提琴链接

  • 您还可以使用`from currency cross join paymenttypes left join source ... group by ...`(根本不使用源数据和联合。) (2认同)