简体   繁体   English

SQL查询:仅在查询中包含行的PAIRS

[英]SQL Query: Only include PAIRS of rows in query

Im looking to find pairs of rows in a table like below 我希望在下面的表格中找到成对的行

MS SQL 2012(maybe 2014) MS SQL 2012(可能是2014年)

Ref, Split
1, A
1, B
2, B
3, A
3, B

Results 结果

Ref, Split
1, A
1, B
3, A
3, B

pairs of rows are partitioned by 'Ref' ie, 1 and 3 need to be returned, but 2 does not have a pair so should not be returned 成对的行由'Ref'分区,即需要返回1和3,但是2没有一对,所以不应返回

I would by default use OVER but i believe this is overkill and not the most effective way of handling this. 我默认使用OVER,但我相信这是矫枉过正,而不是最有效的处理方式。

What are the alternatives 有什么选择

Why not use a self-join and put the results in one row? 为什么不使用自联接并将结果放在一行?

select t1.ref, t1.split, t2.split
from t t1 join 
     t t2
     on t1.ref = t2.ref;

Or if you want the original rows use exists : 或者,如果您希望原始行使用exists

select t.*
from t
where exists (select 1 from t t2 where t2.ref = t.ref and t2.split <> t.split);

If your DBMS supports count() over() it's just the way to go. 如果你的DBMS支持count() over()那就是你要走的路。

select t.Ref, t.Split
from (
   select Ref, Split, count(distinct Split) over(partition by Ref) cnt
) t
where t.cnt > 1 
-- cnt = 2  if exactly the pairs are required

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM