我有一个简单的数据库来模拟电影租赁服务。我有以下3个选择查询,它们可以自行完成:
计算所有租金收入:
SELECT SUM(PRICE) AS RENTAL_REVENUE
FROM RENTAL
输出:
+----------------+
| RENTAL_REVENUE |
+----------------+
| 39.92 |
+----------------+
计算所支付滞纳金的所有收入:
SELECT SUM(NULLIF(LATEFEE, 0)) AS PAID_LATE_FEES
FROM RENTAL
WHERE RETURNED = 1
输出:
+----------------+
| PAID_LATE_FEES |
+----------------+
| 2.99 |
+----------------+
计算所有尚未支付的滞纳金的总和:
SELECT SUM(NULLIF(LATEFEE, 0)) AS OUTSTANDING_LATE_FEES
FROM RENTAL
WHERE RETURNED = 0
输出:
+-----------------------+
| OUTSTANDING_LATE_FEES |
+-----------------------+
| 5.98 |
+-----------------------+
我想将这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;
有更好的方法吗?
答案 0 :(得分:5)
您可以使用SUM
或CASE-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)