首页 > 解决方案 > Postgresql - CTE 加入 cte 并排序

问题描述

我的 sql 文件中有两个 CTE:


    /*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;

标签: postgresqlcommon-table-expression

解决方案


推荐阅读