简体   繁体   English

T-SQL比较一组行与其他行

[英]T-SQL Compare a group of rows with other groups of rows

So I'm trying to filter one table by the values of multiple rows grouped by one column which match multiple rows of another table which are grouped by a column. 因此,我试图通过按一列分组的多行的值来过滤一个表,该值与按列分组的另一张表的多行相匹配。 For Exmaple: 例如:

###Table1###
+--------+-------+
| Symbol | Value |
+--------+-------+
| A      |     1 |
| A      |     2 |
| A      |     3 |
| B      |     9 |
| B      |     8 |
+--------+-------+

###Table2###
+--------+-------+
| Symbol | Value |
+--------+-------+
| C      |     9 |
| C      |     8 |
| D      |     1 |
| D      |     2 |
| D      |     4 |
| E      |     9 |
| E      |     8 |
| F      |     1 |
| F      |     2 |
| F      |     3 |
+--------+-------+

The query needs to return C, E, and F but not D because the values for A match the values of F, and the values of B match the values of C and E. 该查询需要返回C,E和F,但不能返回D,因为A的值与F的值匹配,而B的值与C和E的值匹配。

I hope this makes sense. 我希望这是有道理的。

You can get the match by joining the tables on the value and then counting the symbols. 您可以通过将表联接到值上然后计数符号来获得匹配项。 For your data, this should work: 对于您的数据,这应该有效:

select t2.symbol, t1.symbol
from (select t1.*, count(*) over (partition by symbol) as cnt
      from table1 t1
     ) t1 join
     table2 t2
     on t1.value = t2.value
group by t1.symbol, t2.symbol, t1.cnt;
having count(*) = t1.cnt

This assumes: 这假定:

  • No duplicates in either table. 在两个表中都没有重复项。
  • You are looking for rows in table2 that match table1 , but table2 could have additional values not in table1 . 您正在寻找table2中与table1匹配的行,但是table2可能具有table1没有的其他值。

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

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