Postgres自我加入多次

时间:2018-02-28 15:22:45

标签: sql postgresql self-join

假设我们有这个表

No      Date                       Value
1       2018-02-20 12:00:00        200
1       2018-02-20 12:05:00        205
2       2018-02-20 12:00:00        205 
2       2018-02-20 12:05:00        200
3       2018-02-20 12:00:00        205
3       2018-02-20 12:05:00        210

我想创建这个

Date                   Value1      Value2       Value3
2018-02-20 12:00:00     200         205          205
2018-02-20 12:05:00     205         200          210

我该如何创建?自我加入?

我试过这个

    select p1.VESSEL_NAME,p1.x_LocalTimeStamp_,p1.RealPowerTotal as   "KW1",p1.LF as "LF1",
p2.RealPowerTotal as "KW2",p2.LF as "LF2",
p3.RealPowerTotal as "KW3",p3.LF as "LF3" 
from Kwhmeters5min as p1 
where p1.x_DGNo_='1' and p1.x_LocalTimeStamp_>='2018-02-01 00:00:00' 
inner join Kwhmeters5min as p2 on p2.VESSEL_NAME=p1.VESSEL_NAME and p2.x_LocalTimeStamp_=p1.x_LocalTimeStamp_
where p2.x_DGNo_='2' 
inner join Kwhmeters5min as p3 on p3.VESSEL_NAME=p1.VESSEL_NAME and p3.x_LocalTimeStamp_=p1.x_LocalTimeStamp_
where p3.x_DGNo_='3' 

但我在"内部"。

附近收到错误

3 个答案:

答案 0 :(得分:0)

您无法在where语句后添加其他联接。以下查询应该有效。

SELECT
p1.VESSEL_NAME,
p1.x_LocalTimeStamp_,
p1.RealPowerTotal AS "KW1",
p1.LF AS "LF1",
p2.RealPowerTotal AS "KW2",
p2.LF AS "LF2",
p3.RealPowerTotal AS "KW3",
p3.LF AS "LF3" 
FROM Kwhmeters5min AS p1 INNER JOIN Kwhmeters5min AS p2 ON p2.VESSEL_NAME = p1.VESSEL_NAME
AND p2.x_LocalTimeStamp_ = p1.x_LocalTimeStamp_
INNER JOIN Kwhmeters5min AS p3 ON p3.VESSEL_NAME = p1.VESSEL_NAME
AND p3.x_LocalTimeStamp_ = p1.x_LocalTimeStamp_
WHERE
    p3.x_DGNo_ = '1'
AND p1.x_DGNo_ = '2'
AND p2.x_DGNo_ = '3'
AND p1.x_LocalTimeStamp_ >= '2018-02-01 00:00:00'

答案 1 :(得分:0)

假设您的表名为public.tbl_test,我会使用窗口函数以postgres方式执行此操作:

select distinct on (public.tbl_test.date)
public.tbl_test.date,
nth_value(public.tbl_test.value,1 ) over (PARTITION by public.tbl_test.date order by public.tbl_test.no rows between unbounded preceding and unbounded following) as value1,
nth_value(public.tbl_test.value,2 ) over (PARTITION by public.tbl_test.date order by public.tbl_test.no rows between unbounded preceding and unbounded following) as value2,
nth_value(public.tbl_test.value,3 ) over (PARTITION by public.tbl_test.date order by public.tbl_test.no rows between unbounded preceding and unbounded following) as value3
from public.tbl_test

答案 2 :(得分:0)

试试这个:  select x_LocalTimeStamp_,array_agg(RealPowerTotal) 来自Kwhmeters5min group by x_LocalTimeStamp _