简体   繁体   中英

return a column name depending upon another column field value in oracle

I have written a code like this:

SELECT
C.*,
CASE
    WHEN C.COST_CENTRE_NAME IS NOT NULL THEN 'YES'
    WHEN C.GL_CODE IS NOT NULL THEN 'YES'
    WHEN C.MATERIAL_CODE IS NOT NULL THEN 'YES'
ELSE
    'NO' END AS DEPENDS_OTHER
FROM
OYSTER3.CAT_RULE_MV C

I want an another column to be added with this named DEPENDS_ON where column value of this column will depend upon the 'yes' or 'no' value of DEPENDS_OTHER. If DEPEND_OTHER column value is YES then it should return the column name for which it comes YES under DEPENDS_OTHER column. I am giving an example below:

id  COST_CENTRE_NAME    GL_CODE MATERIAL_CODE   depends_other   depend_on
1         a                                          yes        COST_CENTRE_NAME                  
2                                                    no
3                         123                        yes          GL_CODE
4                                   a2               yes         MATERIAL_CODE
5                                                     no

Just repeat what you have started:

select c.*
      ,case
          when c.cost_centre_name is not null then
           'YES'
          when c.gl_code is not null then
           'YES'
          when c.material_code is not null then
           'YES'
          else
           'NO'
       end as depends_other
      ,case
          when c.cost_centre_name is not null then
           'COST_CENTRE_NAME'
          when c.gl_code is not null then
           'GL_CODE'
          when c.material_code is not null then
           'MATERIAL_CODE'
          else
           null
       end as depends_on
  from oyster3.cat_rule_mv c

TRY THIS

SELECT
C.*,
CASE
    WHEN C.COST_CENTRE_NAME IS NOT NULL THEN 'YES'
    WHEN C.GL_CODE IS NOT NULL THEN 'YES'
    WHEN C.MATERIAL_CODE IS NOT NULL THEN 'YES'
ELSE
    'NO' END AS DEPENDS_OTHER,
CASE
    WHEN C.COST_CENTRE_NAME IS NOT NULL THEN 'COST_CENTRE_NAME'
    WHEN C.GL_CODE IS NOT NULL THEN 'GL_CODE'
    WHEN C.MATERIAL_CODE IS NOT NULL THEN 'MATERIAL_CODE'
ELSE
    ' ' END AS DEPENDS_ON

FROM
OYSTER3.CAT_RULE_MV C

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM