Postgres同一表的连接

3
我有一个长这样的表格:
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值的重复数据?


X和Y列的逻辑是什么? - Vamsi Prabhala
如果 x 为真,则 y 为假,反之亦然,但这是多余的,最初只是一个提示,指出值来自何处,但我不关心两个值来自哪里,因为我需要 x 和 y 来计算,所以我希望得到与结果相同类型和年份的 x 和 y。 - aldr
4个回答

6

你不需要额外做任何事情,只需在连接上添加一些附加约束即可。你真的不想使用子查询,因为这会导致无谓的性能损失。

 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;

4
您可以使用聚合:
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

2
假设 xy 是实际的布尔类型列:
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


1
子查询:
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

1
我接受了你的答案,因为它符合我的思路,但GurV的答案非常优雅和聪明。 - aldr
不需要子查询,请不要在您的代码中使用它。请查看我的答案,那是一个更好的解决方案。 - Michael Hibay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接