【问题标题】:how to concat year =2019 and period=6 to give 20106 and not 20196 number and year =2018 , period=3112 to give 20183112如何连接 year =2019 和 period=6 给出 20106 而不是 20196 数字和 year =2018 , period=3112 给出 20183112
【发布时间】:2020-03-31 06:12:36
【问题描述】:

我需要根据 tiemperiod 连接两个表。
这样 table1.dateperiod =table2.(期间和年份的组合)
即 201906=201906 (2019 年月份是 6 两个整数) 即 20183112=20183112

问题是如何在 period 为 6 时连接它们,这样连接后它将是 201906 而不是 20196 和

表 1

ID  NAME    DATE_PERIOD
1   conan   201906
1   conan   202012
1   conan   20183112
2   andy    201903

表2

ID  PROFILE YEAR    PERIOD
1   host    2019    6
1   writer  2018    3112
1   anchor  2020    12
2   sidekic 2019    3

请参考这个 db fiddle -here

select
 *
from table2 t2
inner join table1 t1 on t1.id = t2.id and t1.date_period= (t2.year*100+t2.period)

预期的解决方案

ID  PROFILE YEAR    MONTH   ID  NAME    DATE_PERIOD
1   anchor  2020    12  1   conan   202012
1   host    2019    6   1   conan   201906
1   sidekick    2020    12  1   andy    202003
1   writer  2018    3112    1   conan   20183112

【问题讨论】:

  • Sybase 还是 Oracle?这是两种截然不同的数据库产品

标签: sql oracle join concatenation sybase


【解决方案1】:

如果它们都是 integer 数据类型,您应该能够通过使用以下方法从年份和月份构造六位数的变体:

year * 100 + month

如果它们是字符数据类型,Oracle 会为此提供一个 lpad 函数,类似于:

concat(year, lpad(month, 2, '0'))

另一方面,Sybase 可以使用replicate 进行填充,但它更丑陋,例如:

year || replicate('0', (2 - char_length(month))) || month

不确定哪个你想要的,因为你给了两个标签。


在您的编辑中,月份也可能采用DDMM 格式,您可以简单地使用模运算来获得最后两个字符。我不会费心在 Oracle/Sybase 中查找该函数,我将把它作为练习留给读者。可以说3112 mod 10012

【讨论】:

  • 我很抱歉。但输入略有变化。我编辑了问题和小提琴。月份列还给出了组合日期和月份,如“ddmm”格式。提供解决方案。感谢您的贡献。
  • 嗨,我不需要 ddmm 的月份。也就是说,如果我们有 2018 和 3112 。我需要 2018312 。或 2017 年和 period=610 那么我需要 20170610
【解决方案2】:

您需要使用LPAD,如下:

select
 *
from table2 t2
inner join table1 t1 
on t1.id = t2.id and t1.date_period= concat(year,LPAD(month,2,0))

db<>fiddle

--更新--

您可以使用CASE声明如下:

select
 *
from table2 t2
inner join table1 t1 on t1.id = t2.id 
and t1.date_period =  concat(year,
                             LPAD(period,
                                  case when length(period) <= 2 
                                       then 2 
                                       else 4 
                                   end,
                                   0))

db<>fiddle

【讨论】:

  • 我很抱歉。但输入略有变化。我编辑了问题和小提琴。月份列还给出了组合日期和月份,如“ddmm”格式。提供解决方案。感谢您的贡献
  • 我很抱歉。我应该提前给出所有可能的场景。
  • 当 year2017 和 period =611 即我需要 20170611 但此 sql 不满足此条件
  • 简单地说,我有数据在第一位省略了零。所以,2018, 3112 需要 20183112。如果 2017 ,208 我需要 20170208
【解决方案3】:

您可以使用以下方法来处理周期长度小于或大于四个的情况

    select
       *
       from table2 t2,table1 t1 
       where t1.id = t2.id 
           and t1.date_period =  concat(year,
                         LPAD(period,
                   decode(length(period),1,2,3,4,length(period))
                               ,
                               0));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    相关资源
    最近更新 更多