指定许多联合COUNT语句的来源

时间:2018-04-08 11:19:45

标签: sql oracle union

我的目标是计算与三个表相关联的记录数,并将结果相互组合。但是,似乎UNION会自动对结果进行排序,因此无法知道哪个结果来自哪个表。

SELECT COUNT(*) FROM ACTM JOIN CUS_CHILD
    ON actm.cust_id = cus_child.cust_id
UNION
SELECT COUNT(*) FROM ACTM JOIN CUS_ADULT
    ON actm.cust_id = cus_adult.cust_id
UNION
SELECT COUNT(*) FROM ACTM JOIN CUS_ELDER
    ON actm.cust_id = cus_elder.cust_id

/* Results in: */
COUNT(*)
    0
    3
    4

我想到了两种可能的解决方案:

  • 使用表名添加列或只添加一些字符串
  • 以某种不同的,可能是矩阵形式显示结果

它们看起来像这样:

Name  | COUNT(*)    Child | Adult | Elder    Child | Adult | Elder
----------------    ---------------------    ---------------------
Child | 3             3       4       0        3       0       0
Adult | 4                                      0       4       0
Elder | 0                                      0       0       0

我尝试重命名每个结果COUNT(*) as "Child"等等以实现中间结果,但它只生成了一个名为Child的列。

所以我不知道如何实现这些,我对SQL很陌生。任何想法都将不胜感激。

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT COUNT(*),
       'Child' as Name FROM ACTM JOIN CUS_CHILD
    ON actm.cust_id = cus_child.cust_id
UNION
SELECT COUNT(*), 
       'Adult ' FROM ACTM JOIN CUS_ADULT
    ON actm.cust_id = cus_adult.cust_id
UNION
SELECT COUNT(*),
       'Elder' FROM ACTM JOIN CUS_ELDER
    ON actm.cust_id = cus_elder.cust_id

OR

SELECT SUM(CASE WHEN CUS_CHILD.cust_id is not null 
            THEN 1
            ELSE 0
        END) AS Child ,
        SUM(CASE WHEN cus_adult.cust_id is not null 
            THEN 1
            ELSE 0
        END) AS Adult  ,
        SUM(CASE WHEN cus_elder.cust_id is not null 
            THEN 1
            ELSE 0
        END) AS Elder  
FROM ACTM 
LEFT JOIN CUS_CHILD
    ON actm.cust_id = cus_child.cust_id
LEFT JOIN CUS_ADULT
    ON actm.cust_id = cus_adult.cust_id
LEFT JOIN CUS_ELDER
    ON actm.cust_id = cus_elder.cust_id

答案 1 :(得分:1)

请勿使用UNION - 除非您想要承担删除重复项的开销。

SQL结果集无序,除非您有明确的ORDER BY。因此,不要依赖于排序,并包含一个列,说明该数字的用途:

SELECT 'child' as which, COUNT(*)
FROM ACTM JOIN
     CUS_CHILD
     ON actm.cust_id = cus_child.cust_id
UNION ALL
SELECT 'adult' as which,  COUNT(*)
FROM ACTM JOIN
     CUS_ADULT
     ON actm.cust_id = cus_adult.cust_id
UNION ALL
SELECT 'elder' as which, COUNT(*)
FROM ACTM JOIN
     CUS_ELDER
     ON actm.cust_id = cus_elder.cust_id;

您也可以制作这些子查询,只需执行以下操作:

SELECT (SELECT COUNT(*)
        FROM ACTM JOIN
            CUS_CHILD
            ON actm.cust_id = cus_child.cust_id
       ) as num_child,
       (SELECT COUNT(*)
        FROM ACTM JOIN
             CUS_ADULT
             ON actm.cust_id = cus_adult.cust_id
       ) as num_adult,
       (SELECT COUNT(*)
        FROM ACTM JOIN
             CUS_ELDER
             ON actm.cust_id = cus_elder.cust_id
       ) as num_elder
FROM dual;