[英]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.