Not sure if Access supports it, but in most engines (including SQL Server
) this is called a correlated subquery and works fine:
SELECT TypesAndBread.Type, TypesAndBread.TBName,
(
SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
FROM Sandwiches
WHERE (Type = 'Sandwich Type' AND Sandwiches.Type = TypesAndBread.TBName)
OR (Type = 'Bread' AND Sandwiches.Bread = TypesAndBread.TBName)
) As SandwichCount
FROM TypesAndBread
This can be made more efficient by indexing Type
and Bread
and distributing the subqueries over the UNION
:
SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Type = [Sandwiches Types].[Sandwich Type]
)
FROM [Sandwiches Types]
UNION ALL
SELECT [Breads].[Bread] As TBName, "Bread" As Type,
(
SELECT COUNT(*) As SandwichCount
FROM Sandwiches
WHERE Sandwiches.Bread = [Breads].[Bread]
)
FROM [Breads]