how to do a SELECT of two different fields of the same table in a single column in Oracle 11g?

1

Good morning, I'm making a query I need to make a selection of 2 fields from the same table but within a single column column, that is

SELECT desc_equipo, serialnro, serialmac from producto

desc_equipo is let's say the field that stores the name or description of the product, depending on the equipment, some have serial but do not have serial, others have serial but do not have serial, then what they ask me to do is put all the data, serialnro and serialmac in a single column. I have tried several ways but all fail me.

Is there a way to resolve this doubt?

Thanks in advance

    
asked by GioV 07.11.2016 в 16:44
source

3 answers

3

Assuming that serialnro and serialmac are of the same type, and only one of the 2 has a value that is not null at a time, then you can use coalesce to return the value that is not a null :

select desc_equipo,
       coalesce(serialnro, serialmac) as serial
  from product

Edition

  

that is, sometimes those who use the system leave a blank space

It's a shame that you have spaces mixed with null to represent a nonexistent value. But if this is the case, you can correct the query by means of an additional trim that converts the empty spaces to null , so that the coalesce works correctly:

select desc_equipo,
       coalesce(trim(serialnro), serialmac) as serial
  from product
    
answered by 07.11.2016 / 16:56
source
2

I feel that the structure of your table is the wrong one, if all the products have a serial but some are nro and others are mac, then you would have a column for the serial and another column to indicate if it is mro or mac, your columns would be:

SERIAL VARCHAR2
SERIAL_TYPE VARCHAR2

and you could add a constraint to the Serial Type column so that it only accepts the values that you define

ALTER TABLE PRODUCT ADD
CONSTRAINT PRODUCT_SERIAL_TYPE_CHK CHECK (PRODUCT_SERIAL IN ('MAC','NRO'))

This way you would eliminate your problems with blank and null spaces, any doubt I am at your orders.

Greetings!

    
answered by 07.11.2016 в 17:33
1

You can also use:

SELECT desc_equipo, TRIM(NVL(serialnro, ' ') || ' ' || NVL(serialmac, ' ')) AS serial
  FROM producto

In case there are both in a registry, they will appear concatenated.

    
answered by 07.11.2016 в 17:03