sql - 如何一次从一个表中进行多个查询并进行数学计算?
问题描述
我想得到以下结果,但很难查询逻辑。我想要的是在从表中删除取消的交易(-负 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
解决方案
就像你说的那样,这将返回所需的结果;第 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>
推荐阅读
- react-native - 如何在反应导航中每次输入焦点
- arangodb - 是否可以使用不完整的单词和 ArangoSearch 查找文档?
- mobile-safari - 为什么我在 LTE 上的移动 Safari 中收到 Opentok 错误 OT_TIMEOUT“Session.publish :: 无法在合理的时间内发布”?
- sql - 您可以在 T-SQL MERGE 部分执行更多操作吗?
- java - 如何使用 ASM 访问内部类的方法?
- ios - 为什么 Game Center 配对控制器卡在“正在连接”?
- css - 在标签内垂直对齐文本的问题
- python - ValueError:无法导入“hostingstart.app”
- javascript - shadow DOM 和 light DOM 中应该包含哪些部分?
- ios - 禁用与 segue 的文本字段交互