Michi :
私はあなたにもで見つけることができ、次の表持ってSQL fiddle
ここに:
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");
私はテーブルから値を取得するには、次のSQLを使用します。
SELECT Product, Inbound_Date, Outbound_Date, Return_Date, sum(Quantity)
FROM Flows
GROUP BY 1,2,3,4;
このすべては、これまで正常に動作します。
しかし、今私は日付が呼ばれる1列に表示されていることを達成したいですFLow_Date
。
結果は次のようになります。
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
私はそれを動作させるために私のコードに変更するには何が必要ですか?
ゴードン・リノフ:
私は、あなただけの必要があると思うcase
表現を:
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;
あなたは、複数の非持つことができる場合、これはより複雑になりNULL
、行ごとに値を。
その場合には、union all
単純な十分なアプローチであります
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;
これは、必ずしも(この場合は)最も効率的な方法ではありませんが、それはうまく動作します。場合はflows
、実際に表示され、その後、選択肢が好まれるかもしれません。