【问题标题】:new table from two different select column results (from the same table) in postgresql来自postgresql中两个不同选择列结果(来自同一个表)的新表
【发布时间】:2022-11-14 20:41:10
【问题描述】:

非常感谢任何帮助。我有一个名为 lifelong 的表,如下所示。

   id           first_meal            last_meal
0   1  2022-07-25 12:28:00  2022-07-25 20:06:00
1   2  2022-07-26 13:12:00  2022-07-26 19:09:00
2   3  2022-07-27 14:13:00  2022-07-27 20:13:00
3   4  2022-07-28 15:10:00  2022-07-28 21:22:00

我从 first_meal 列中跳过一行

 select  f.id, f.first_meal  from lifelong   f offset 1;

我从 last_meal 列中选择所有

 select id, last_meal from lifelong

现在,我需要将这两个不同的选择从同一个表中保存为一个新表

我尝试了 union 或 union all,我尝试将这两个选择放在括号中 - 到目前为止没有结果

【问题讨论】:

    标签: postgresql join select


    【解决方案1】:

    您可以在联合查询的帮助下尝试INSERT INTO ... SELECT

    INSERT INTO newTable (id, meal)
    (SELECT id, first_meal
     FROM lifelong
     ORDER BY first_meal
     OFFSET 1)
    UNION ALL
    SELECT id, last_meal
    FROM lifelong;
    

    请注意,使用 OFFSET 而不使用 ORDER BY 没有多大意义。我假设您想排除first_meal 日期排序的第一行。

    【讨论】:

    • 非常感谢您的帮助。本质上,我跳过了 first_meal 列的第一行,以最终获得今天的 first_meal 和昨天的 last_meal 之间的时间增量。澄清一下,您在 newTable 中只指定了两列,但是,我有 3 个结果列 id、first_meal、last_meal。对不起一个愚蠢的问题,但我确实事先创建了 newTable 对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    相关资源
    最近更新 更多