WITH

时间:2019-10-08 03:15:19

标签: postgresql

我在Postgre上有SELECT个查询,其中包含WITH个子查询作为json列。我需要根据WITH子查询json数据或列对查询结果进行排序。

这是我运行的示例查询:

SELECT 
    person.id,
    ( WITH person_warehouse AS (
             SELECT count(warehouse.id) AS total_warehouse,
                    sum((warehouse.detailinfo -> 'total_area'::text)::numeric) AS total_area_storage
             FROM warehouse
             WHERE warehouse.owner_id = person.id
             GROUP BY warehouse.owner_id
            )
     SELECT row_to_json(person_warehouse .*) AS json_tree
       FROM person_warehouse) AS warehousedata,
FROM 
  person
ORDER BY warehousedata->>'total_warehouse' DESC

但是返回的是仓库数据不是列。如何根据子查询结果对选择查询进行排序?

谢谢

1 个答案:

答案 0 :(得分:0)

您可以在ORDER BY子句中引用别名,但是不能在表达式中使用该别名。您必须从SELECT列表中重复该表达式。

此查询以非常复杂的方式编写,可能写得更简单:

SELECT person.id,
       json_build_object(
          'total_warehouse',
          count(warehouse.id),
          'total_area_storage',
          sum((warehouse.detailinfo ->> 'total_area')::numeric)
       ) AS warehousedata
FROM person
   LEFT JOIN warehouse
      ON warehouse.owner_id = person.id
GROUP BY person_id
ORDER BY count(warehouse.id) DESC;

如果您真的想将ORDER BY子句排序为字符串,请进行类型转换。