两个计数语句之间的区别

时间:2017-01-31 10:14:44

标签: sql oracle

我在SQL中有两个count语句,我希望得到它们之间的区别。我正在尝试这样的事情。

SELECT  'Customers After', SUM(Counts) Counts
FROM
(SELECT 'Customers Before', COUNT(*) AS Counts FROM CUSTOM3
MINUS
SELECT  'Customers to be', COUNT(*) AS Counts FROM
CUSTOM3 a
WHERE 
    a.CUSTOMER_FLAG IS NULL
AND NOT EXISTS (SELECT 1 FROM ACC2 acc WHERE acc.CUSTOMER_ID = a.CUSTOMER_ID)
AND CUST_BQ IS NULL);

但是它只是返回行数,我应该使用什么而不是MINUS,或者我应该如何启动它?

我应该得到这样的东西:

Customers After 15
Customers Before 20
Customers to be 5

3 个答案:

答案 0 :(得分:4)

使用子查询和案例表达式:

SELECT Customers_before, Customers_after,
       Customers_before - Customers_after As Customers_to_be
FROM (
    SELECT count(*) As Customers_before,
           count( case when a.CUSTOMER_FLAG IS NULL
                       and not exists( 
                            SELECT 1 FROM ACC2 acc 
                            WHERE acc.CUSTOMER_ID = a.CUSTOMER_ID)
                       and CUST_BQ IS NULL
                   then 1 end ) as Customers_after
    FROM CUSTOM3 a
)

答案 1 :(得分:3)

执行此操作时:

SELECT 'Customers Before', COUNT(*)
MINUS
SELECT  'Customers to be', COUNT(*)

... minus没有做任何事情,因为第二个查询中的第一列值不相同。即使该字符串相同,您也可以看到相同的数据(如果计数不同)或者没有返回任何行(如果计数相同)。我认为你只是误解了what the minus set operator does

如果您想要计算差值,则需要减去它们的值:

SELECT  'Customers After',
  (SELECT COUNT(*) FROM CUSTOM3)
  - (SELECT COUNT(*) FROM CUSTOM3 a
      WHERE a.CUSTOMER_FLAG IS NULL
      AND NOT EXISTS (SELECT 1 FROM ACC2 acc WHERE acc.CUSTOMER_ID = a.CUSTOMER_ID)
      AND CUST_BQ IS NULL) Counts
FROM dual;

或仅计算不匹配'减去'的行数。标准(验证空处理):

SELECT  'Customers After', COUNT(*) AS Counts
FROM CUSTOM3 a
WHERE NOT (a.CUSTOMER_FLAG IS NULL
AND NOT EXISTS (SELECT 1 FROM ACC2 acc WHERE acc.CUSTOMER_ID = a.CUSTOMER_ID)
AND CUST_BQ IS NULL);

SELECT  'Customers After', COUNT(*) AS Counts
FROM CUSTOM3 a
WHERE a.CUSTOMER_FLAG IS NOT NULL
OR EXISTS (SELECT 1 FROM ACC2 acc WHERE acc.CUSTOMER_ID = a.CUSTOMER_ID)
OR CUST_BQ IS NOT NULL;

或者如果您确实想要查看结果集中的所有三个计数,请使用子查询,如@krokodilko所示。

答案 2 :(得分:0)

我喜欢使用with的代码,对我来说似乎更清楚:

with cb as (SELECT COUNT(*) AS Counts FROM CUSTOM3),
     ctb as (SELECT COUNT(*) AS Counts FROM CUSTOM3 a
WHERE a.CUSTOMER_FLAG IS NULL
AND NOT EXISTS (SELECT 1 FROM ACC2 acc WHERE acc.CUSTOMER_ID = a.CUSTOMER_ID)
AND CUST_BQ IS NULL)
     select 'Customers Before' as description, counts from cb union all
     select 'Customers to be' as description, counts from ctb union all
     select 'Customers After' as description, cb.counts - ctb.counts as counts from cb, ctb