Oracle SQL检索列基于同一表中的条件

时间:2017-06-14 16:38:09

标签: sql oracle

我有一个Oracle视图,需要用它来填充页面上的不同名称。使用相同的数据库列根据搜索条件填充页面的名称。分配给名称的值仅取决于搜索条件。为了使这更具体,这是一个例子

EMPLOYEE_ID  DEPT    ROLE_TYPE       GROUP_TYPE
 123          IT     DEVELOPER        SUPPORT
 111          IT     DEVELOPER        APPL_SERVICES
 145          IT     QA               APPL_SERVICES
 222          IT     WEB              APPL_SERVICES
 322          IT     WEB              SUPPORT

此表填充的字段名称/类别如下

     WEB SUPPORT SERVICES 
     WEB APPLICATION SERVICES 
     DEVELOPER APPLICATION SERVICES
     DEVELOPER SUPPORT SERVICES
     QA APPLICATION SERVICES
     QA SUPPORT SERVICES

使用SQL过滤器的逻辑如下:

 where ROLE_TYPE='DEVELOPER' AND GROUP_TYPE='APPL_SERVICES'
 Then assign employee 111 to  DEVELOPER APPLICATION SERVICES

 where ROLE_TYPE='DEVELOPER' AND GROUP_TYPE='SUPPORT'
 Then assign employee 123 to  DEVELOPER SUPPORT SERVICES

 where ROLE_TYPE='WEB' AND GROUP_TYPE='SUPPORT'
 Then assign employee 322 to  WEB SUPPORT SERVICES

 where ROLE_TYPE='WEB' AND GROUP_TYPE='APPL_SERVICES'
 Then assign employee 222 to  WEB APPLICATION SERVICES

 and so on..

我的问题是,在不进行多次查询的情况下,构建查询的最佳方法是什么?我不想为每个条件编写单独的查询。

为了澄清我的意思,这里是UI显示的样子:

USER           FUNCTION         POSITION            GROUP







123      DEVELOPER SUPPORT SERVICES          DEVELOPER       SUPPORT SERVICES

谢谢

2 个答案:

答案 0 :(得分:1)

您只需使用case

select t.*, 
       (case when ROLE_TYPE = 'DEVELOPER' AND GROUP_TYPE = 'APPL_SERVICES'
             then 'DEVELOPER APPLICATION SERVICES'
             when  ROLE_TYPE ='DEVELOPER' AND GROUP_TYPE = 'SUPPORT'
             then 'DEVELOPER SUPPORT SERVICES'
             when ROLE_TYPE = 'WEB' AND GROUP_TYPE = 'SUPPORT'
             then 'WEB SUPPORT SERVICES'
             when ROLE_TYPE = 'WEB' AND GROUP_TYPE = 'APPL_SERVICES'
             then 'WEB APPLICATION SERVICES'
        end) as new_group
from . . .

答案 1 :(得分:0)

DECODE函数将逐个比较每个列值。如果要根据单个语句进行比较,可以使用它:

select 
  a.*,
  decode(a.employee_id,
    123,'DEVELOPER SUPPORT SERVICES',
    111,'DEVELOPER APPLICATION SERVICE',
    145,'QA Application services',
    222,'WEB Application service',
    322,'WEB SUPPORT SERVICES'
  ) as new_group 
from table_name a;