SQL 加入帮助所需的字段类型与持续时间信息不匹配

SQL Join help needed field type doesn't match for duration information

我正在尝试将两个 table 与 SQL 连接起来。我希望将 table 2 的成本添加到 table 1。过去成本仅因服务而异,因此这是一个简单的连接,但数据已更改,现在成本也因服务而异根据位置和持续时间。

我可以 link 基于位置而不是持续时间。 Table 1 中的持续时间存储为整数。在 table 2 中,持续时间以“xx-xxxx”格式存储为文本范围。我尝试使用 substring/left 和 patindex 隔离新字段中的最短持续时间和最长持续时间。 (我正在使用通过 dbeaver 访问的缓存数据库,但无法使用 charindex)。

我能够将最短持续时间提取为“-”字符之前的文本,但无法提取最大持续时间,即使我有它我也不确定如何加入 table秒。请帮忙!另外由于正在使用数据库,我目前只能写select语句,不能写create/edit tables。谢谢!

Table 1:

Table 2:

期望的输出:

这是一个糟糕的设计。您不应该将数字范围存储为字符串。相反,您应该在两个不同的列中设置上限和下限。

您的数据存储方式,您需要拆分字符串并将每个部分转换为数字,以便您可以与第一个 table 中的值进行比较。所以:

select t1.*, t2.cost
from table1 t1
inner join table2 t2 
    on t2.duration between cast(substring(duration, 1, instr(duration, '-') - 1) as int) 
                       and cast(substring(duration, instr(duration, '-') + 1) as int)