Transpose columns to rows in query if table contains NULL values

Michi :

DB Fiddle

CREATE TABLE logistics (
    id int primary key,
    campaign VARCHAR(255),
    inbound_date VARCHAR(255),
    outbound_date VARCHAR(255)
);

INSERT INTO logistics
(id, campaign, inbound_date, outbound_date)
VALUES 
("1", "C001", "2019-01-01", "2019-02-08"),
("2", "C001", "2019-05-10", "2019-05-12"),
("3", "C001", "2019-06-12", NULL),
("4", "C001", NULL, "2019-06-15"),
("5", "C002", "2019-11-14", "2019-11-22"),
("6", "C002", NULL, "2019-12-13"),
("7", "C002", NULL, NULL);

In the table above I have the columns inbound_date and outbound_date.
Now, I want to transpose them to one column called event_type.

Expected Result

Campaign     event_type          event_date
C001         inbound_date        2019-01-01
C001         outbound_date       2019-02-08
C001         inbound_date        2019-05-10
C001         outbound_date       2019-05-12
C001         inbound_date        2019-06-12
C001         outbound_date       2019-06-15
C002         inbound_date        2019-11-14
C002         outbound_date       2019-11-22
C002         outbound_date       2019-12-13

First, I tried to go with the solution form this question:

select campaign,
       (case when inbound_date is not null then 'inbound_date' 
             when outbound_date is not null then 'outbound_date'
        end) event_date,
       (case when inbound_date is not null then inbound_date
             when outbound_date is not null then outbound_date
        end) as event_date
from logistics;

Second, I tried it with the solution from here:

SELECT campaign,
       coalesce(inbound_date, outbound_date) as event_date
FROM logistics;

With both queries I do not get any result.
I assume the issue is somehow the NULL values in the table.
How can I get the expected result?

Gordon Linoff :

Here is one method:

select campaign, 'inbound_date' as event_type,  inbound_date as event_date
from logistics
where inbound_date is not null
union all
select campaign, 'outbound_date' as event_type,  outbound_date as event_date
from logistics
where outbound_date is not null;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=19520&siteId=1