将3列总和合并为一个表

时间:2016-11-02 06:40:54

标签: sql oracle join oracle11g

我有一个简单的数据库来模拟电影租赁服务。我有以下3个选择查询,它们可以自行完成:

  1. 计算所有租金收入:

    SELECT SUM(PRICE) AS RENTAL_REVENUE
        FROM RENTAL
    

    输出:

        +----------------+
        | RENTAL_REVENUE |
        +----------------+
        |      39.92     |
        +----------------+
    
  2. 计算所支付滞纳金的所有收入:

    SELECT SUM(NULLIF(LATEFEE, 0)) AS PAID_LATE_FEES
        FROM RENTAL
        WHERE RETURNED = 1
    

    输出:

        +----------------+
        | PAID_LATE_FEES |
        +----------------+
        |       2.99     |
        +----------------+
    
  3. 计算所有尚未支付的滞纳金的总和:

    SELECT SUM(NULLIF(LATEFEE, 0)) AS OUTSTANDING_LATE_FEES
        FROM RENTAL
        WHERE RETURNED = 0
    

    输出:

        +-----------------------+
        | OUTSTANDING_LATE_FEES |
        +-----------------------+
        |          5.98         |
        +-----------------------+
    
  4. 我想将这3个查询的结果合并到一个包含3列的表中,如下所示:

    +----------------+----------------+-----------------------+
    | RENTAL_REVENUE | PAID_LATE_FEES | OUTSTANDING_LATE_FEES |
    +----------------+----------------+-----------------------+
    |      39.92     |       2.99     |          5.98         |
    +----------------+----------------+-----------------------+
    

    我能够通过以下查询实现此目的,但1 = 1无意义向我暗示可能有更好的方法。

    SELECT rental_revenue + paid_late_fees + outstanding_late_fees AS TOTAL_REVENUE, 
           rental_revenue, 
           paid_late_fees, 
           outstanding_late_fees 
    FROM   (SELECT SUM(price) AS RENTAL_REVENUE 
            FROM   rental) 
           inner join (SELECT SUM(Nullif(latefee, 0)) AS PAID_LATE_FEES 
                       FROM   rental 
                       WHERE  returned = 1) 
                   ON 1 = 1 
           inner join (SELECT SUM(Nullif(latefee, 0)) AS OUTSTANDING_LATE_FEES 
                       FROM   rental 
                       WHERE  returned = 0) 
                   ON 1 = 1;
    

    有更好的方法吗?

2 个答案:

答案 0 :(得分:5)

您可以使用SUMCASE-WHEN选择所有记录并在DECODE内构建过滤器:

SELECT SUM(price) AS rental_revenue,
       SUM(CASE 
             WHEN returned = 1 AND latefee <> 0 THEN latefee
             ELSE 0
           END) AS paid_late_fees,
       SUM(CASE
             WHEN returned = 0 AND latefee <> 0 THEN latefee
             ELSE 0
           END) AS outstanding_late_fees             
FROM rental

答案 1 :(得分:2)

您只需使用case表达式或decode()函数

即可
select sum(price) as return_revenue
     , sum(case 
             when returned = 1 
             then latefee
           end)  as paid_late_fees
     , sum(case
            when returned = 0
            then latefee
           end)  as outstanding_late_fees           
  from rental