我有一个易于分组的查询。我需要将具有完全相同记录的组添加到另一个表(关系)。
我在SQL Server下使用ANSI-SQL,但我接受任何实现的答案。
例如:
表1:
Id | Value
---+------
1 | 1
1 | 2
1 | 3
2 | 4
3 | 2
4 | 3
表2:
Value | ...
------+------
1 | ...
2 | ...
3 | ...
在我的例子中,结果是:
Id |
---+
1 |
想象它可能是代码:
SELECT Table1.Id
FROM Table1
GROUP BY Table1.Id
HAVING ...? -- The group that has exactly the same elements of Table2
提前致谢!
答案 0 :(得分:0)
要获得相同的集合,请使用内部联接:
SELECT Table1.Id
FROM Table1
INNER JOIN table2 ON table1.id=table2.id
GROUP BY Table1.Id
HAVING ...? --
答案 1 :(得分:0)
您可以尝试以下操作:
select t1.Id
from Table2 t2
join Table1 t1 on t1.value = t2.value
group by t1.Id
having count(distinct t1.value) = (select count(*) from Table2)
答案 2 :(得分:0)
CREATE TABLE#T1(ID INT,[Values] INT)INSERT INTO#T1 VALUES(1,1),(1,2),(1,3),(2,4),(2,5) ,(3,6)
CREATE TABLE#T2([Values] INT)INSERT INTO#T2 VALUES(1),(2),(3),(4)
SELECT * FROM#T1
SELECT * FROM#T2
SELECT A.ID 从 (SELECT ID,COUNT(DISTINCT [Values])AS Count FROM#T1 GROUP BY ID )A
JOIN ( SELECT T1.ID,COUNT(DISTINCT T2。[Values])计数 从#T1 T1 加入#t2 T2 ON T1。[值] = T2。[值] GROUP BY T1.ID )B ON A.ID = B.ID和A.Count = B.Count