我正在大学实践中研究一个问题,但不知道如何实现所需的输出。我对SQL比较陌生,正在使用Oracle 11g。
我有一个名为CUSTOMERS的表,我想对其运行三个查询以获取每个表的总计数
CUSTOMERS (customer#, lastname, firstname, address, city, state, zip, referred, region)
三个查询本身可以很好地执行并产生所需的结果,但是我需要找到一种方法来组合它们以产生具有三列的单个结果以及每一列中每个查询的结果。
SELECT COUNT(*) AS "Total Customers"
FROM CUSTOMERS;
SELECT COUNT(*) AS "Direct Customers"
FROM CUSTOMERS
WHERE referred IS NOT NULL;
SELECT COUNT(*) AS "Referred Customers"
FROM CUSTOMERS
WHERE referred IS NULL;
我花了最后几个小时在这里和其他网站上阅读,但是无法理解。我怀疑可能需要JOIN或UNION。
答案 0 :(得分:1)
使用单个查询进行条件聚合:
SELECT
COUNT(*) AS "Total Customers",
COUNT(referred) AS "Direct Customers",
COUNT(CASE WHEN referred IS NULL THEN 1 END) AS "Referred Customers"
FROM CUSTOMERS;