postgres加入同一张桌子

时间:2017-03-24 14:05:25

标签: sql postgresql

我有一张看起来像这样的表

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的双线

4 个答案:

答案 0 :(得分:2)

您可以使用聚合:

    (function($) {
    	$(document).ready(function() {
    		var width = $(document).width();
    		$(window).resize(function() {
    			//do something
    			if (width < 900) {
    				$('div#frame-1').css('bottom', 1900);
    				$('div#frame-1').attr('data-ps-vertical-position', '1900');
    			} else if (width > 901) {
    				$('div#frame-1').css('bottom', 2500);
    				$('div#frame-1').attr('data-ps-vertical-position', '2500');
    			}
    		}).resize();
    	});
    })(jQuery);

答案 1 :(得分: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

答案 2 :(得分:1)

您不需要做任何额外的事情,但在连接上添加一些额外的约束。你真的不想做子查询,因为无缘无故地打击了性能。

 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;

答案 3 :(得分:0)

子查询:

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