我想通过一个连接的字段来命令。
例如:
SELECT DISTINCT(field1 ||' '||field2) AS field3 from Table ORDER BY field1;
这可以用其他方式吗?我收到一条错误,指出我无法通过未选择的字段进行排序。
有没有办法选择一个字段,但让它不可见,以便我可以通过它进行ORDER BY?
答案 0 :(得分:2)
这可以使用子查询或CTE来完成:
子查询:
SELECT c.field3
FROM (SELECT DISTINCT(field1 ||' '||field2) AS field3 from Table) c
ORDER BY c.field3;
CTE:
WITH ConcatTable AS (
SELECT DISTINCT(field1 ||' '||field2) AS field3 from Table
)
SELECT field3 FROM ConcatTable ORDER BY field3;
也可以通过简单地重复选择的表达式来完成,但由于代码重复,我不喜欢这样做:
SELECT DISTINCT(field1 ||' '||field2)
FROM Table
ORDER BY field1 ||' '||field2;
======编辑=========
正如评论中所指出的,连接字段的排序与仅仅按字段1排序并不完全相同。如果你真的想按field1排序,你必须做这样的事情:
子查询:
SELECT c.field3
FROM (SELECT DISTINCT field1, (field1 ||' '||field2) AS field3 from Table) c
ORDER BY c.field1;
CTE:
WITH ConcatTable AS (
SELECT DISTINCT field1, (field1 ||' '||field2) AS field3 from Table
)
SELECT field3 FROM ConcatTable ORDER BY field1;