postgresql - Postgresql - CTE 加入 cte 并排序
问题描述
我的 sql 文件中有两个 CTE:
- 第一个在库存中找到电影的总成本。如果库存中有 8 份 DVD 电影,每份成本 10 美元,那么它输出 80 作为总成本。
- 第二个找到电影的总收入。如果一部电影被租了 20 次,每次租金是 5 美元,那么它输出 100 作为收入。
- 然后使用这些 CTE,我需要通过计算 total_revenue - total_cost 找到最赚钱的 10 部电影。total_cost 和 total_revenue 有效,但当我加入它们时它不起作用。存在语法错误。
/*TOTAL COST OF FILMS */
WITH total_cost AS (
select "films"."filmId",
"films"."title",
count("inventory"."inventoryId") as "numberOfCopies",
sum("films"."replacementCost") as "totalCost"
from "films"
join "inventory" using ("filmId")
group by ("films"."filmId");
order by "totalCost" desc
limit 10;
)
/* TOTAL REVENUE FROM FILMS */
WITH total_revenue AS (
select "films"."filmId",
"films"."title",
count("rentals"."rentalId") as "numberOfRentals",
sum ("films"."rentalRate") as "totalRevenue"
from "films"
join "inventory" using ("filmId")
join "rentals" using ("inventoryId")
group by ("films"."filmId");
order by "totalRevenue" desc
limit 10;
)
select "films"."filmId",
"films"."title",
"total_revenue"."totalRevenue" - "total_cost"."totalCost" as "profit"
from "films"
join "total_cost" using ("filmId")
join "total_revenue" using ("filmId")
group by "films"."filmId"
order by "profit" desc
limit 10;
解决方案
推荐阅读
- c++ - 如何解决着色器的问题?
- r - str_extract_all 返回一个列表,但我想要数据框中的一列
- java - Java Swing - JTree 和 JLabel 如何相互通信?
- html - 使用 jsPdf 和 Html2Canvas 在 Angular 中将 HTML 页面转换为 PDF
- python-3.x - 使用 Azure 机器学习服务注册和下载 fastText .bin 模型失败
- java - Kafka CommitFailedException 分别运行具有不同主题的 2 个消费者时
- html - 嵌套在另一个 div 中的 div 不可见
- c# - 不支持带有 Autofac throw IServiceProvider 的 Net core 3.0
- asp.net-mvc - 将数据从单个视图发布到两个模型类
- ansible - 如何从 ansible_facts 获取“cifs”挂载的“用户名”?