问题是使用to_char将按日期按顺序按顺序转换为ascii。例如:
SELECT foo, bar FROM baz ORDER BY foo;
我想使用to_char格式化foo,但这样做会影响顺序:
SELECT to_char(foo,'dd/MM/yyyy') as foo, bar FROM baz ORDER BY foo;
因为foo现在是文本类型。有办法正确地做到这一点吗?或者只在代码中?
答案 0 :(得分:4)
正确而简单的解决方案是:
SELECT to_char(b.foo,'dd/MM/yyyy') as foo, b.bar
FROM baz b
ORDER BY b.foo;
格式化日期列foo
是查询计划程序的全新列,恰好与表列foo
冲突。在ORDER BY和GROUP BY子句中,输出列的名称优先于表列。非限定名称foo
将引用输出列。
要使用ORDER BY子句中的原始表列,只需表限定列。
我对所有表格列进行了表格限定以澄清我的观点。只有在这种情况下才能在ORDER BY子句中使用。表别名b
只是为了方便。
答案 1 :(得分:2)
您可以为格式化列使用不同的别名:
SELECT to_char(foo,'dd/MM/yyyy') as formatted_foo,
bar
FROM baz
ORDER BY foo;
作为替代方案,如果你需要保留foo别名:
select foo,
bar
from (
SELECT to_char(foo,'dd/MM/yyyy') as foo,
foo as foo_date
bar
FROM baz
) t
order by foo_date
答案 2 :(得分:1)
有什么问题
SELECT foo AS foo_date, to_char(foo,'dd/MM/yyyy') AS foo, bar
FROM baz
ORDER BY foo_date;
答案 3 :(得分:-1)
两次不拉foo的替代方法是:
SELECT
to_char(foo,'dd/MM/yyyy') AS foo -- Alias precedes original column name
,bar
FROM
baz
ORDER BY
CAST(foo AS DATE) -- Explicit cast ensures date order instead of text
;
本机的PostgreSQL版本将是:
SELECT
to_char(foo,'dd/MM/yyyy') AS foo -- Alias precedes original column name
,bar
FROM
baz
ORDER BY
foo::DATE -- Explicit cast ensures date order instead of text
;