SQL-使用前面列中的值进行减法
我有一个查询,其中列出了国家名称、每个国家/地区的客户总数和活动客户数(它们存在于销售表中) 我需要一个列,其中应计算非活动客户的数量,但由于不能在同一select语句中使用已定义的别名,因此我陷入了困境 以下是查询:SQL-使用前面列中的值进行减法,sql,oracle,Sql,Oracle,我有一个查询,其中列出了国家名称、每个国家/地区的客户总数和活动客户数(它们存在于销售表中) 我需要一个列,其中应计算非活动客户的数量,但由于不能在同一select语句中使用已定义的别名,因此我陷入了困境 以下是查询: SELECT country_name , COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS ,
SELECT country_name , COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS ,
COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
FROM countries ctr JOIN customers cust
ON (cust.country_id = ctr.country_id)
LEFT JOIN sales sh
ON (sh.cust_id = cust.cust_id)
GROUP BY country name
我应该如何处理这个问题 根据您的方法,您可以:
SELECT ctr.country_name,
COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS,
COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
(COUNT(DISTINCT cust.cust_id) - COUNT(DISTINCT sh.cust_id)) AS NUM_INACTIVE_CUSTOMERS
FROM countries ctr JOIN
customers cust
ON cust.country_id = ctr.country_id LEFT JOIN
sales sh
ON sh.cust_id = cust.cust_id
GROUP BY ctr.country_name;
为了提高性能,我建议在加入之前进行聚合:
SELECT ctr.country_name,
COUNT(cust.cust_id) AS TOTAL_NUM_CUSTOMERS,
COUNT(sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
(COUNT(cust.cust_id) - COUNT(sh.cust_id)) AS NUM_INACTIVE_CUSTOMERS
FROM countries ctr JOIN
customers cust
ON cust.country_id = ctr.country_id LEFT JOIN
(SELECT DISTINCT cust_id
FROM sales sh
) sh
ON sh.cust_id = cust.cust_id
GROUP BY country_name;
这样就不需要使用此情况下的计数(独立)
子查询:
SELECT country_name,TOTAL_NUM_CUSTOMERS,NUM_ACTIVE_CUSTOMERS,
(TOTAL_NUM_CUSTOMERS-ACTIVE_CUSTOMERS) AS INACTIVE_CUSTOMERS FROM (
SELECT country_name , COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS ,
COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
FROM countries ctr JOIN customers cust
ON (cust.country_id = ctr.country_id)
LEFT JOIN sales sh
ON (sh.cust_id = cust.cust_id)
GROUP BY country name ) AS A
将查询包装在外部查询中;这将允许您使用列别名:
SELECT t.*,
TOTAL_NUM_CUSTOMERS - NUM_ACTIVE_CUSTOMERS AS NUM_INACTIVE_CUSTOMERS
FROM (
SELECT country_name,
COUNT(DISTINCT cust.cust_id) AS TOTAL_NUM_CUSTOMERS,
COUNT(DISTINCT sh.cust_id) AS NUM_ACTIVE_CUSTOMERS
FROM countries ctr
JOIN customers cust
ON (cust.country_id = ctr.country_id)
LEFT JOIN sales sh
ON (sh.cust_id = cust.cust_id)
GROUP BY country name
) t
您可以减去查询中的2个计数。编辑您的问题并提供示例数据和结果。计数(不同的cust.cust\u id)-计数(不同的sh.cust\u id)-像这样?我也这么认为,但SQLDeveloper说这是语法错误,出于某种原因不让我这么做谢谢,我实际上已经重新安装了SQLDeveloper,现在减法工作正常,但我没有考虑在加入之前进行聚合,再次感谢