我正在尝试按列连接两个表,并按同一列对表进行排序。
以下是这两个表中的一些示例数据:
表.x
state
00039
01156
表.y
state
39
1156
如何在 SQL 助手中加入和排序表?
我正在尝试按列连接两个表,并按同一列对表进行排序。
以下是这两个表中的一些示例数据:
表.x
state
00039
01156
表.y
state
39
1156
如何在 SQL 助手中加入和排序表?
最简单的解决方案是将双方都转换integer
为@Andrew提到的,因此您可以使用简单的转换,或者trycast(...)
尝试转换值,如果失败不会返回错误,而是返回NULL
值:
select *
from x
inner join y on
trycast(y.state as integer) = trycast(y.state as integer)
order by y.state
旧答案(为了将来的读者以及您可以/不能做什么而将其留在这里):
如果您有最新版本的 Teradata(您没有指定它),您也将拥有LPAD
功能。假设这y.state
不是文本,而是一个数字,我们还需要转换它,因为 lpad 将字符串作为参数。如果是,请省略cast(...)
:
select *
from x
inner join y on
x.state = lpad(cast(y.state as varchar(5)), 5, '0')
order by y.state
如果你没有LPAD
函数,那么一些脏代码substring
可能会派上用场:
select *
from x
inner join y on
x.state = substring('00000' from char_length(cast(y.state as varchar(5))+1) || cast(y.state as varchar(5)
order by y.state
以上假设您存储的数字最多为 5 位。如果超出该数字(您的示例数据为 5),那么您需要调整代码。