如何在Postgres Sql中以不同的格式选择相同的列两次?

时间:2018-06-07 09:27:02

标签: postgresql

我想要实际的列值以及截断的列值,如下所示。任何人都可以提供帮助。

Select "sub1"."TimestampField","month_trunc1","month_trunc2" 
from (
   Select  "Id", date_trunc('month', "TimestampField") as "month_trunc1", "TimestampField" 
   from "Table"
) as "sub1", (
  Select  "Id", date_trunc('month', "TimestampField") as "month_trunc2", "TimestampField" 
  from "Table"
) as "sub2" 
WHERE "month_trunc2" = ("month_trunc1"+interval '1 month');

1 个答案:

答案 0 :(得分:0)

您可以通过在同一个表上使用JOIN来简化示例:

 SELSECT 
   "sub1"."mainfield",
   "sub1"."TimestampField" as month1, 
   "sub2"."TimestampField" as month2, 
   date_trunc('month', "sub1"."TimestampField") as "month_trunc1", 
   date_trunc('month', "sub2"."TimestampField") as "month_trunc2"
 FROM "Table" "sub1" 
 JOIN "Table" "sub2"
       ON "month_trunc2" = ("month_trunc1"+interval '1 month');