[sql] A select query selecting a select statement

I don't even know if I am doing this query the right way. There is a Sandwiches table that has some 7 fields and 2 of them are comboboxes (Type and Bread).

So I made a query that combines all of the comboboxes values into one query, like this:

SELECT TypesAndBreads.TBName, TypesAndBreads.Type
FROM (SELECT [Sandwiches Types].[Sandwich Type] As TBName, "Sandwich Type" As Type
    FROM [Sandwiches Types]
UNION ALL
    SELECT Breads.Bread As TBName, "Bread" As Type 
    FROM Breads)  AS TypesAndBreads;

I get the flat values of the tables now I want to count all the sandwiches under each TypesAndBreads.TBName. I have this, just to make sure it works with all the Sandwiches:

SELECT TypesAndBread.Type, TypesAndBread.TBName,
       (SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM Sandwiches) As SandwichCount
FROM TypesAndBread;

But I want to reference the current Type and TBName inside the subquery. Something like this:

SELECT TypesAndBread.Type, TypesAndBread.TBName,
       (SELECT Count(Sandwiches.[SandwichID]) As SandwichCount
        FROM Sandwiches
        WHERE Sandwiches.[TypesAndBread.Type] = Sandwiches.[TypesAndBread.TBName]) As SandwichCount
FROM TypesAndBread;

But of course this doesn't work. I didn't think it will, just thought of giving it a try. I was thinking of maybe constructing the query with VBA when they open the Report that this query is going to be based of.

So I guess my question is: Is there a way to reference the current selected fields in a subquery? Or is there a different way to approach this?

Thanks for the help

EDIT: My table structure is like this:

Sandwiches's fields

| SandwichID | Name | Date Added | Chef | Sandwich Type | Bread | Reviewed By |

where Sandwich Type and Bread are Lookup fields for these tables:

Sandwiches Types's fields

| Sandwich Type |

Breads's fields

| Bread |

The TypesAndBreads query combined the Sandwiches Types and Breads tables, but the reason for that is so that I can get the count of all the sandwiches that have that Type or bread. A result like this:

+=============================================+
|      Type     |    TBName   | SandwichCount |
+=============================================+
| Sandwich Type | Turkey Club |            10 |
| Bread         | Italian     |             5 |
| Bread         | Garlic      |             8 |
+---------------------------------------------+

the example result's first row basicly says there are 10 sandwiches in record with the Sandwich Type field equal to Turkey Club.

I hope that explains it better.

This question is related to sql ms-access select ms-access-2007

The answer is


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]

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.


Examples related to sql

Passing multiple values for same variable in stored procedure SQL permissions for roles Generic XSLT Search and Replace template Access And/Or exclusions Pyspark: Filter dataframe based on multiple conditions Subtracting 1 day from a timestamp date PYODBC--Data source name not found and no default driver specified select rows in sql with latest date for each ID repeated multiple times ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database

Examples related to ms-access

How to get parameter value for date/time column from empty MaskedTextBox Access And/Or exclusions Get length of array? How to pass an array to a function in VBA? How to insert values into the database table using VBA in MS access Access 2013 - Cannot open a database created with a previous version of your application Does VBA contain a comment block syntax? java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why? Manipulating an Access database from Java without ODBC How to find longest string in the table column data

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to ms-access-2007

C# Inserting Data from a form into an access Database How to show row number in Access query like ROW_NUMBER in SQL Import an Excel worksheet into Access using VBA How to refer to Excel objects in Access VBA? Retrieve column values of the selected row of a multicolumn Access listbox Determine whether a Access checkbox is checked or not Now() function with time trim How do I correctly use "Not Equal" in MS Access? A select query selecting a select statement Use SELECT inside an UPDATE query