在postgresql中按顺序使用长度(计算列)

wd2eg0qa  于 2021-07-24  发布在  Java
关注(0)|答案(3)|浏览(640)
SELECT  concat(first_name,last_name)  AS full_name from customer
ORDER BY  length(full_name);

我试着在postgresql数据库中运行这个。我给我这个错误

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

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

nkcskrwz

nkcskrwz1#

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;
s5a0g9ez

s5a0g9ez2#

你能试试下面的一种吗?

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))
gkl3eglg

gkl3eglg3#

这将起作用,并避免重复使用 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)

相关问题