用表中的数据替换硬编码值

时间:2017-03-28 02:15:00

标签: sql oracle

目前,我在查询中有3个附加链接硬编码。它们充当了层次结构:1 = Faculty, 2 = Staff, 3 = Student。如果affiliations_tbl表中的用户具有多个联盟(例如:同时也是学生的工作人员),则它将使用其工作人员从属关系,因为它在使用{{1}定义的层次结构中更高}和partition by

decode()

我创建了一个存储联属组SELECT x2.emplid, scc_afl_code FROM (SELECT x.emplid, scc_afl_code, row_number() over(partition BY x.emplid ORDER BY x.affil_order) r FROM (SELECT t.emplid, scc_afl_code, DECODE(scc_afl_code, 'FACULTY', 1, 'STAFF', 2, 'STUDENT', 3, 999) affil_order FROM affiliations_tbl t WHERE t.scc_afl_code IN (SELECT a.scc_afl_code FROM affiliation_groups_tbl a WHERE a.group = 'COLLEGE')) x) x2 WHERE x2.r = 1; 的表,因此我可以通过向表中添加数据来扩展它,而不是更改此查询中的硬编码值。示例:我将其添加到表中,而不是将affiliation_groups_tbl添加到'CONSULTANT', 4列表中,因此我不必修改SQL。

decode()

我已经更新了查询的后半部分,只选择scc_afl_code | group | group_name | sort_order -------------+---------+------------+----------- FACULTY | COLLEGE | Faculty | 1 STAFF | COLLEGE | Staff | 2 STUDENT | COLLEGE | Student | 3 组中的scc_afl_code如何正确更新查询的第一部分以将该表用作层次结构?

2 个答案:

答案 0 :(得分:1)

尝试下面的代码,而不是在语句的select子句中解码:

coalesce((
    select g.sort_order 
    from affiliation_groups_tbl g
    where g.scc_afl_code = t.scc_afl_code ), 999)

答案 1 :(得分:1)

你可以尝试那样

    create table dictionary
    (id number,
    code varchar2(32),
    name varchar2(32),
    sort number);

    insert into dictionary (id, code, name, sort) values (16, 'B', 'B name', 1);
    insert into dictionary (id, code, name, sort) values (23, 'A', 'A name', 2);
    insert into dictionary (id, code, name, sort) values (15, 'C', 'C name', 4);
    insert into dictionary (id, code, name, sort) values (22, 'D', 'D name', 3);

    select partition,
           string,
           decode(string, 'B', 1, 'A', 2, 'D', 3, 'C', 4, 999) decode,
           row_number() over(partition by partition order by decode(string, 'B', 1, 'A', 2, 'D', 3, 'C', 4, 999)) ordering
      from (select mod(level, 3) partition, chr(65 + mod(level, 5)) string
              from dual
            connect by level <= 8)
    minus

    -- Alternate --
    select partition,
           string,
           nvl(t.sort, 999) nvl,
           row_number() over(partition by partition order by nvl(t.sort, 999)) ordering
      from (select mod(level, 3) partition, chr(65 + mod(level, 5)) string
              from dual
            connect by level <= 8) r
      left join dictionary t
        on t.code = r.string;