【问题标题】:Query to return zero if nothing exist如果不存在,则查询返回零
【发布时间】:2015-02-22 22:38:39
【问题描述】:

我有一张包含货币、付款类型和发票金额的表格。我必须编写查询以获取货币、付款类型和总发票金额。这对于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

我的查询是 Select currency, paymenttype, sum(invoiceamount) as total from table group by currency, 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

如何做到这一点?

【问题讨论】:

    标签: sql sql-server-2008 join


    【解决方案1】:

    您可以使用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;
    

    【讨论】:

      【解决方案2】:

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

      然后您只需在 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;
      

      【讨论】:

      • 这对我的数据不起作用。尽管我发现我的查询是 select aa.Currency,aa.PaymentType,sum(bb.amount) from (select * from (select distinct paymenttype from payment) a cross join (select distinct currency from payment) c) aa left join payment bb on aa.PaymentType = bb.PaymentType and aa.Currency = bb.Currency group by aa.PaymentType,aa.Currency order by aa.Currency
      猜你喜欢
      • 2019-02-15
      • 1970-01-01
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-17
      • 1970-01-01
      相关资源
      最近更新 更多