SQL服务器,如何在只显示部分字符串的情况下按完整字符串排序?
SQL Server, how to order by full string while only showing part of it?
我有这样的数据:
Column_1
'(A) Top Sort'
'(B) Second Sort'
'(C) Third custom Sort'
添加字母是为了让客户分类。我有不止三个字母,但我会保留完整的字母集作为示例。
我这样做是为了仅显示文本:
Select
right(Column_1, len(column_1) -4) as 'Column_1'
from Table_1
order by Column_1 ASC
但结果是按右排序(Column_1, len(column_1) -4), 而不是全字段:
Column_1
Second Sort
Third Custom Sort
Top Sort
我快疯了。我想按查询中未显示的内容对其进行排序。不知道该怎么做。如何按完整字符串对其进行排序并仅显示部分字符串?
编辑 - 这是 union all 语句的顶部部分。只有一个其他部分,它永远是最后一个(字母 Z)
只需在 order by
中包含 table 别名:
Select right(Column_1, len(column_1) -4) as Column_1
from Table_1
order by table_1.Column_1 ASC;
问题是 Column_1
本身可以引用 SELECT
中定义的别名或 table 中的列。您的 SQL 引擎正在将其解析为别名。
另一个解决方案是只给列一个不同的别名,这样就没有命名冲突:
Select right(Column_1, len(column_1) -4) as new_Column_1
from Table_1
order by Column_1 ASC;
因为在 SELECT
列表中找不到 Column_1
,名称将解析为 table 中的列。
您不能使用 union all
语句执行此操作。为此,您需要一个子查询:
select . . ., right(Column_1, len(column_1) -4) as column_1
from ((select . . ., column_1 -- no SUBSTRING!
from table1
) union all
(select . . .
)
) t
order by t.column_1;
我有这样的数据:
Column_1
'(A) Top Sort'
'(B) Second Sort'
'(C) Third custom Sort'
添加字母是为了让客户分类。我有不止三个字母,但我会保留完整的字母集作为示例。
我这样做是为了仅显示文本:
Select
right(Column_1, len(column_1) -4) as 'Column_1'
from Table_1
order by Column_1 ASC
但结果是按右排序(Column_1, len(column_1) -4), 而不是全字段:
Column_1
Second Sort
Third Custom Sort
Top Sort
我快疯了。我想按查询中未显示的内容对其进行排序。不知道该怎么做。如何按完整字符串对其进行排序并仅显示部分字符串?
编辑 - 这是 union all 语句的顶部部分。只有一个其他部分,它永远是最后一个(字母 Z)
只需在 order by
中包含 table 别名:
Select right(Column_1, len(column_1) -4) as Column_1
from Table_1
order by table_1.Column_1 ASC;
问题是 Column_1
本身可以引用 SELECT
中定义的别名或 table 中的列。您的 SQL 引擎正在将其解析为别名。
另一个解决方案是只给列一个不同的别名,这样就没有命名冲突:
Select right(Column_1, len(column_1) -4) as new_Column_1
from Table_1
order by Column_1 ASC;
因为在 SELECT
列表中找不到 Column_1
,名称将解析为 table 中的列。
您不能使用 union all
语句执行此操作。为此,您需要一个子查询:
select . . ., right(Column_1, len(column_1) -4) as column_1
from ((select . . ., column_1 -- no SUBSTRING!
from table1
) union all
(select . . .
)
) t
order by t.column_1;