SQL - 使用先前列中的值进行替代

时间:2017-06-26 11:50:58

标签: sql oracle

我有一个查询,其中列出了国家/地区名称,每个国家/地区的客户总数以及活跃客户数量(它们存在于销售表中)。

我需要一个列,其中应该计算非活动客户的数量,但由于不能在同一个select语句中使用已定义的别名,所以我被卡住了

以下是查询:

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

我该如何处理这个问题?

3 个答案:

答案 0 :(得分:0)

根据你的方法,你会这样做:

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;

为了提高性能,我建议在join之前进行聚合:

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;

这样就无需count(distinct)

答案 1 :(得分:0)

在这种情况下使用子查询:

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

答案 2 :(得分:0)

在外部查询中包装查询;这将允许您使用列别名:

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