首页 > 解决方案 > 如何一次从一个表中进行多个查询并进行数学计算?

问题描述

我想得到以下结果,但很难查询逻辑。我想要的是在从表中删除取消的交易(-负 custnb)后获得交易/发票的确切数量。所以对于我的示例表,我有 5 个事务,2 个被取消,所以我只想得到 3 个。

想要的结果

Invoices     Customers

3            3

桌子

invoicenumber         custnb     invoiceid

    1001              1          1001
    1002              2          1002
    1003              1          1003
    1004              5          1004
    1005              2          1005
    2000001           -1         1001
    2000002           -2         1002

标签: sqloracle

解决方案


就像你说的那样,这将返回所需的结果;第 1 - 9 行代表样本数据,因此您需要的代码从第 10 行开始。

SQL> with test (invoicenumber, custnb, invoiceid) as
  2    (select 1001,  1, 1001 from dual union all
  3     select 1002,  2, 1002 from dual union all
  4     select 1003,  1, 1003 from dual union all
  5     select 1004,  5, 1004 from dual union all
  6     select 1005,  2, 1005 from dual union all
  7     select 2001, -1, 1001 from dual union all
  8     select 2002, -2, 1002 from dual
  9    )
 10  select count(invoicenumber) invoices,
 11         count(custnb) customers
 12  from test
 13  where custnb > 0
 14    and invoicenumber not in (select invoiceid
 15                              from test
 16                              where custnb < 0
 17                             )
 18  ;

  INVOICES  CUSTOMERS
---------- ----------
         3          3

SQL>

推荐阅读