在 Postgres 的 ORDER BY 中使用 LENGTH(计算列)sql

Using LENGTH(computed column) in ORDER BY in Postgres sql

SELECT  concat(first_name,last_name)  AS full_name from customer
ORDER BY  length(full_name);

我试图在 postgre sql 数据库中 运行 这个。 我给我这个错误

[42703] ERROR: column "full_name" does not exist

我该如何解决?按全名长度排序行。

能否请您尝试以下任一方法?

SELECT  concat(first_name,last_name) COLLATE "C"  AS full_name from customer
ORDER BY  length(full_name)

SELECT  concat(first_name,last_name)  from customer
ORDER BY  length(concat(first_name,last_name))

这会起作用,并且避免了 concat()

的双重使用
WITH results AS (
  SELECT concat(first_name, last_name) AS full_name FROM customer
)
SELECT full_name FROM results ORDER BY length(full_name)

Postgres 通过允许列别名作为 order by 键来遵守标准。所以这有效:

SELECT  CONCAT(first_name, last_name)  AS full_name
FROM customer
ORDER BY full_name;

但是,它不会使用别名将其扩展到 表达式。您可以使用子查询或 CTE 解决此问题。我可能还建议横向连接:

SELECT v.full_name
FROM customer c CROSS JOIN LATERAL
     (VALUES (CONCAT(c.first_name, c.last_name))) v(full_name)
ORDER BY v.full_name;