Transpose column names to rows and put values in seperate column

Michi :

I have the following table which you can also find in the SQL fiddle here:

CREATE TABLE Flows (
    Product TEXT,
    Inbound_Date DATE,
    Outbound_Date DATE,
    Return_Date DATE,
    Quantity VARCHAR(255)
);

INSERT INTO Flows
(Product, Inbound_Date, Outbound_Date, Return_Date, Quantity)
VALUES 

("Product A", "2019-01-01", NULL, NULL, "400"),
("Product A", NULL, "2019-05-08", NULL, "200"),
("Product A", NULL, NULL, "2019-06-25", "600"),

("Product B", "2019-03-08", NULL, NULL, "380"),
("Product B", NULL, "2019-03-15", NULL, "120"),
("Product B", NULL, NULL, "2019-04-17", "610");

I use the following SQL to get the values from the table:

SELECT Product, Inbound_Date, Outbound_Date, Return_Date, sum(Quantity)
FROM Flows
GROUP BY 1,2,3,4;

All this works fine so far.


However, now I want to achieve that the dates are displayed in one column called FLow_Date.
The result should look like this:

Product          Date_Type            Flow_Date
Product A        Inbound_Date        2019-01-01
Product A        Oubound_Date        2019-05-08
Product A        Return_Date         2019-06-25
Product B        Inbound_Date        2019-03-08
Product B        Outbound_Date       2019-03-15
Product B        Return_Date         2019-04-17

What do I need to change in my code to make it work?

Gordon Linoff :

I think you just need case expressions:

select f.product,
       (case when inbound_date is not null then 'inbound_date' 
             when outbound_date is not null then 'outbound_date'
             when return_date is not null then 'return_date'
        end) date_type,
       (case when inbound_date is not null then inbound_date
             when outbound_date is not null then outbound_date
             when return_date is not null then return_date
        end) as flow_date
from flows f;

This becomes more complicated if you can have multiple non-NULL values per row.

In that case, union all is a simple enough approach

select fd.*
from ((select f.product, 'inbound_date' as date_type, inbound_date as flow_date
       from flows f
      ) union all
      (select f.product, 'outbound_date' as date_type, outbound_date as flow_date
       from flows f
      ) union all
      (select f.product, 'return_date' as date_type, return_date as flow_date
       from flows f
      )
     ) fd
where flow_date is not null;

This is not necessarily the most efficient method (in this case), but it works well. If flows is really a view, then alternatives might be preferred.

Guess you like

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