给出以下SQL Server架构:
CREATE TABLE #TableA (Id int);
CREATE TABLE #TableB (Id int, TableA_Id int, Status_Id int)
CREATE TABLE #Statuses (Id int)
SELECT
*
FROM
#TableA AS A
INNER JOIN #TableB AS B
ON A.Id = B.TableA_Id
INNER JOIN #Statuses AS S
ON B.Status_Id = S.Id
如何获取TableA
中dbo.Statuses
中每行至少有一个条目的#TableA
中的所有行?
例如,在以下数据集中,只应返回#TableA
[1]
[2]
[3]
[4]
#Statuses
[1]
[2]
[3]
#TableB
[1][1][1]
[2][1][3]
[3][2][1]
[4][2][2]
[5][2][3]
[6][3][1]
的第2行:
{{1}}
答案 0 :(得分:1)
SELECT B.TableA_Id
FROM #Statuses S
LEFT JOIN #TableB B
ON B.Status_Id = S.Id
GROUP BY B.TableA_Id
HAVING COUNT(DISTINCT S.Id) = COUNT(DISTINCT B.Status_Id)
答案 1 :(得分:1)
你可以用简单的" where
条款。假设#TableB
中的状态列仅具有有效状态值:
select a.*
from #TableA a
where (select count(*) from statuses) =
(select count(distinct status) from #TableB b where b.TableA_Id = a.id);
你可以放松这个假设。这是一种方式:
select a.*
from #TableA a join
(select count(*) as numstatuses from #statuses) s
where (select count(distinct b.status)
from #TableB b join
#statuses s
on b.id = s.id
where b.TableA_Id = a.id
) = numstatuses
答案 2 :(得分:0)
SELECT TableA_Id
FROM TableB
GROUP BY TableA_Id
HAVING COUNT(*) >= (SELECT COUNT(*) FROM Statuses);