【问题标题】:Select columns based on a CSV in another table根据另一个表中的 CSV 选择列
【发布时间】:2013-05-24 21:15:03
【问题描述】:

我有一个包含以下内容的表格:

表1

ID Range        Rate
1  A,B,C,D,E,F   1.2
2  A,B,C         3.1 

还有一张桌子:

表2

ID A B C D E F G H J K
1  1 2 1 3 4 2 4 5 8 1     
2  1 2 1 3 4 2 4 5 8 1     

基本上,这告诉我们可以将速率应用于哪些列,例如,我们可以将速率 1.2 应用于存储在 table2 的 A、B、C、D、E、F 列中的值,并且应该应用 3.2 的速率仅适用于 A、B 和 C 列。

我正在加入ID列上的两个表

Select * From Table1 
Inner Join Table2 ON Table1.ID = Table2.ID

但我想要实现的是在加入 2 个表之后,根据 Table1 的 Range 列的内容从 Table2 中选择列。

基于上面的例子,从 Table1 第一列的范围字段有:A,B,C,D,E,F 所以从 Table2 中,我试图只选择列 A,B,C,D,E ,F 并将比率 (1.2) 应用于所有列,其余列保持不变,因此解决方案将如下所示:

ID A       B     C      D      E      F      G  H   J  K
1  1*1.2  2*1.2  1*1.2  3*1.2  4*1.2  2*1.2  4  5   8  1
2  1*3.1  2*3.1  1*3.1  3      4      2      4  5   8  1 

希望这是有道理的。

谢谢

【问题讨论】:

  • 而您正试图在单个 SQL 选择语句中执行此操作?
  • 这些表几乎肯定应该被规范化。在对数据一无所知的情况下很难确定。
  • 不必在单个 SQL 中,不幸的是,规范化目前不是一个选项。
  • 结果数据去哪了?如果这是我最后的选择,我个人只会尝试使用 SQL 或 PL/SQL。
  • 结果被插入到另一个表中。

标签: sql oracle plsql oracle10g


【解决方案1】:

您正在以逗号分隔的列表中查找子字符串。执行此操作的 SQL 标准方法是使用 like:

select t2.id,
       t2.a * (case when ','||Range||',' like '%,A,%' then t1.rate else 1 else end) as a,
       t2.b * (case when ','||Range||',' like '%,B,%' then t1.rate else 1 else end) as b,
       t2.c * (case when ','||Range||',' like '%,C,%' then t1.rate else 1 else end) as c,
       t2.d * (case when ','||Range||',' like '%,D,%' then t1.rate else 1 else end) as d,
       t2.e * (case when ','||Range||',' like '%,E,%' then t1.rate else 1 else end) as e,
       t2.f * (case when ','||Range||',' like '%,F,%' then t1.rate else 1 else end) as f,
       t2.g * (case when ','||Range||',' like '%,G,%' then t1.rate else 1 else end) as g,
       t2.h * (case when ','||Range||',' like '%,H,%' then t1.rate else 1 else end) as h,
       t2.j * (case when ','||Range||',' like '%,J,%' then t1.rate else 1 else end) as j,
       t2.k * (case when ','||Range||',' like '%,K,%' then t1.rate else 1 else end) as k
from Table1 t1 left join
     Table2 t2
     on t1.id = t2.id;

具体来说,这是分隔范围,因此每个值前后都有一个逗号(包括第一个和最后一个)。然后它会为每个值寻找一个模式。

我应该提到,这种类型的查询表明数据结构不佳。您的 Table1 的每个值应该有单独的行。

【讨论】:

    【解决方案2】:

    不是很好(很脆),但是:

    select  case when 'A' in t1.Range then t2.a * t1.rate else t2.a else end a,
            case when 'B' in t1.Range then t2.b * t1.rate else t2.b else end b,
            case when 'C' in t1.Range then t2.c * t1.rate else t2.c else end c,
            case when 'D' in t1.Range then t2.d * t1.rate else t2.d else end d,
            ...
    from    Table1 t1 left join Table2 t2 on t1.id = t2.id
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-30
      • 2021-06-11
      • 2020-02-16
      • 2022-01-06
      • 2015-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多