Sql 将具有多个属性的行转换为每行具有一个属性的行

Sql 将具有多个属性的行转换为每行具有一个属性的行,sql,postgresql,postgresql-9.5,unpivot,Sql,Postgresql,Postgresql 9.5,Unpivot,我有以下表格: Id | Arrival | Departure | Expected Return ------------------------------------------------- 1 | 2019/8/2 | 2019/8/10 | 2019/8/15 2 | 2019/8/1 | 2019/8/15 | 2019/8/22 3 | 2019/8/2 | 2019/8/16 | 2019/8/21 但是,我需要一个

我有以下表格:

Id    |   Arrival  |  Departure | Expected Return
-------------------------------------------------
1     | 2019/8/2   | 2019/8/10  | 2019/8/15
2     | 2019/8/1   | 2019/8/15  | 2019/8/22
3     | 2019/8/2   | 2019/8/16  | 2019/8/21 
但是,我需要一个返回如下内容的查询(理想情况下不需要定义其他函数)

与所有工会:

select Id, 'Arrival' "Action", Arrival Date from tablename
union all
select Id, 'Departure' "Action", Departure Date from tablename
union all
select Id, 'Expected Return' "Action", "Expected Return" Date from tablename
order by Id, Date
请参阅。
结果:

编辑。
使用<代码>值可能更有效(尽管不简单):

请参阅带有UNION ALL的。

select Id, 'Arrival' "Action", Arrival Date from tablename
union all
select Id, 'Departure' "Action", Departure Date from tablename
union all
select Id, 'Expected Return' "Action", "Expected Return" Date from tablename
order by Id, Date
请参阅。
结果:

编辑。
使用<代码>值可能更有效(尽管不简单):


请参阅。

sh*t!。。。聪明的方法,没想到。我会测试并让你知道。它工作得很好,只是想知道是否有办法让它更有效。谢谢你的时间。这就是我试图弄明白的,在我对你最初的方法的简单感到惊讶之前。这很好,不过老实说,我很难理解。横向连接不容易掌握,这就是为什么我发布了文档链接,但如果你用谷歌搜索它,你可以找到更多。如果您发现第一个查询效率很高,请使用它,因为它更具可读性和可维护性。sh*t!。。。聪明的方法,没想到。我会测试并让你知道。它工作得很好,只是想知道是否有办法让它更有效。谢谢你的时间。这就是我试图弄明白的,在我对你最初的方法的简单感到惊讶之前。这很好,不过老实说,我很难理解。横向连接不容易掌握,这就是为什么我发布了文档链接,但如果你用谷歌搜索它,你可以找到更多。如果您发现第一个查询非常有效,请使用它,因为它更具可读性和可维护性。
| id  | Action          | date       |
| --- | --------------- | -----------|
| 1   | Arrival         | 2019-08-02 |
| 1   | Departure       | 2019-08-10 |
| 1   | Expected Return | 2019-08-15 |
| 2   | Arrival         | 2019-08-01 |
| 2   | Departure       | 2019-08-15 |
| 2   | Expected Return | 2019-08-22 |
| 3   | Arrival         | 2019-08-02 |
| 3   | Departure       | 2019-08-16 |
| 3   | Expected Return | 2019-08-21 |
select t.id, v.*
from tablename t, 
  lateral (values
    ('Arrival', t.Arrival),
    ('Departure', t.Departure),
    ('Expected Return', t."Expected Return")
   ) v (Action, Date);