T-SQL 比较一组行和其他几组行
T-SQL Compare a group of rows with other groups of rows
所以我试图通过按一列分组的多行的值来过滤一个 table,这些值与按列分组的另一 table 的多行相匹配。例如:
###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 |
+--------+-------+
查询需要 return C、E 和 F 而不是 D,因为 A 的值与 F 的值匹配,而 B 的值与 C 和 E 的值匹配。
我希望这是有道理的。
您可以通过在值上连接 table 然后计算符号来获得匹配。对于您的数据,这应该有效:
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
假设:
- table 中没有重复项。
- 您正在
table2
中查找与 table1
匹配的行,但 table2
可能有 table1
中没有的其他值。
所以我试图通过按一列分组的多行的值来过滤一个 table,这些值与按列分组的另一 table 的多行相匹配。例如:
###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 |
+--------+-------+
查询需要 return C、E 和 F 而不是 D,因为 A 的值与 F 的值匹配,而 B 的值与 C 和 E 的值匹配。
我希望这是有道理的。
您可以通过在值上连接 table 然后计算符号来获得匹配。对于您的数据,这应该有效:
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
假设:
- table 中没有重复项。
- 您正在
table2
中查找与table1
匹配的行,但table2
可能有table1
中没有的其他值。