[英]postgres join on same table
我有一張看起來像這樣的桌子
years type value x y
1 b 3.74637 false true
1 b -0.52816 true false
1 mon1 0 true false
1 mon1 0 false true
1 mon10 0.00413 true false
1 mon10 0.00137 false true
我希望桌子看起來像
years type x y
1 b 3.74637 -0.52816
1 mon1 0 0
1 mon10 0.00413 0.00137
因此,我創建了一個請求,在該請求上我自己連接了表
SELECT
i.years,
i.type,
i.value as b,
j.value as m
from abc as i
inner join abc as j on i.type = j.type AND i.years = j.years
WHERE i.type = j.type AND i.m = j.b
現在我明白了
years type x y
1 b 3.74637 -0.52816
1 b -0.52816 3.74637
1 mon1 0 0
1 mon1 0 0
1 mon10 0.00413 0.00137
1 mon10 0.00137 0.00413
我如何擺脫線的x值等於下一行的y的雙峰
您可以使用聚合:
Select years, type,
Max (case when x then value end)as x,
Max (case when y then value end)as y
From t
Group by years, type
假設x
和y
是真實的布爾列:
select xv.years, xv.type, xv.value as x, yv.value as y
from abc xv
join abc yv on (xv.years, xv.type) = (yv.years, yv.type) and yv.y
where xv.x;
在線示例: http : //rextester.com/TUQPQH27415
您無需執行任何其他操作,只需在聯接上添加一些其他約束即可。 您確實不希望執行子查詢,因為毫無原因會導致性能下降。
SELECT
i.years,
i.type,
i.value as b,
j.value as m
from abc i
inner join abc j on i.type = j.type and i.x = true and j.y = true;
子查詢:
select x1.*, y2.y
from
(
select years, type, value as x
from MyTable
where x = 'true'
) x1
left join
(
select years, type, value as y
from MyTable
where y = 'true'
) y2
on x1.years = y2.years
and x1.type = y2.type
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.