当我的表格中有3列时," t" (X,Y,Z),我想看到每一行,其中X中的值x在Y列中,但是对于Z中的相同z。
e.g。
X Y Z
1 2 1
1 1 1
2 1 2
这里的结果将是第一行,因为" 1"在" 1"。
的相同z的第二行中为Y. 我尝试过类似的事情:select * from t
where X = any (select Y from t)
group by z;
但这显然是错误的。
编辑:更好的例子:
X | Y | Z
-----+---------+------------
1 | 2 | 1
6 | 1 | 6
9 | 2 | 9
3 | 1 | 1
9 | 1 | 9
返回表应该如下所示
X | Y | Z
-----+---------+------------
1 | 2 | 1
因为只有第一行的x值在Y的某处,Z = 1。
答案 0 :(得分:1)
试试这个:
declare @tb table(x int,y int,z int)
insert into @tb
select 1 ,2, 1 union all
select 1 ,1 ,1 union all
select 2, 1, 2
select a.z,a.x,b.y from @tb as a
inner join @tb b
on a.x= b.y
group by a.z, a.x, b.y
结果:
1 1 1
2 2 2
当我用来编辑您的查询时:
declare @tb table(x int,y int,z int)
insert into @tb
select 1 ,2, 1 union all
select 1 ,1 ,1 union all
select 2, 1, 2
select * from @tb
where x = any (select y from @tb)
group by z,x,y;
结果:
1 1 1
1 2 1
2 1 2
答案 1 :(得分:0)
我会这样做:
select t.*
from t
where t.x in (select t2.y from t t2 where t2.z = t.z);
这似乎是将您的问题直接翻译成SQL。