【问题标题】:decode multiple conditions in oracle/sql在 oracle/sql 中解码多个条件
【发布时间】:2014-09-01 08:55:09
【问题描述】:

我有这个表包含:

id number = unique per user
code = c (calendar) or f (fiscal)
start_month = 1 to 12
date_created

我该怎么做才能解码归档期限:

例如如果用户被标记为 C 且 start_month = 1,则第 1 季度的归档期限为“3”,第 2 季度为 6,第 3 季度为 9,第 4 季度为 12。

如果用户标记为 F 且 start_month =2,则归档期限为第 1 季度 = 4、第 2 季度 = 7、第 3 季度 = 10、第 4 季度 = 1

【问题讨论】:

  • 假设表 1 被命名为 table1,我的选择是:select id_number, code, start_month, qtr1, qtr2, qtr3, qtr4---第一 3 列将从 table1 中选择而值对于 qtr1-4 应该来自使用解码功能....不能使用这种情况,因为正在使用的 oracle 版本有点旧.. :-)
  • 对不起,但这不是我想要的。我不明白为什么code = C and start_month = 1 给你3, 6, 9, 12code = F and start_month = 2 给你4, 7, 10, 1。你能解释一下那个逻辑吗(在其他情况下,更好的是伪算法)。如果可能的话,code=F and start_month = 3 会发生什么?或者你给出的2个案例是唯一可以存在的?
  • 抱歉...如果代码为 C 且 start_month = 1,则 qtrs(1,2,3,4) 将始终为 3、6、9 和 12..但如果代码为 F 并且start_month = 2,则 qtrs 将始终为 4,7,10,1...如果代码为 F 且 start_month = 3,则 qtrs 将始终为 5,8,11,2...如果代码为 F 且 start_month = 4,那么 qtrs 将是 6,9,12,3...etch...
  • 所以我看不出 C 和 F 与您的样本有任何区别......看起来只有 start_month 有影响。
  • 好的,那么当它是日历时它没有影响。所以如果code = C and start_month = 5,你也会得到3、6、9、12

标签: sql oracle decode


【解决方案1】:

我的第一个想法是将 start_month 转换为日期并使用 add_months(),但当然,如果您不能使用 case,那么您的版本早于 8i,您也将无法使用 add_months()。

任何数学家都会对以下使用 div 和 mod 13 感到震惊,但如果我正确理解您想要实现的目标,我认为这将适用于 Oracle 7 和可能的旧版本:

select decode ( code, 'c', 3,
                      'f', trunc((2+start_month)/13) + mod((2+start_month),13)) as qtr1,
       decode ( code, 'c', 6,
                      'f', trunc((5+start_month)/13) + mod((5+start_month),13)) as qtr2,
       decode ( code, 'c', 9,
                      'f', trunc((8+start_month)/13) + mod((8+start_month),13)) as qtr3,
       decode ( code, 'c', 12,
                      'f', trunc((11+start_month)/13) + mod((11+start_month),13)) as qtr4,
etc...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多