A select query selecting a select statement

后端 未结 2 943
鱼传尺愫
鱼传尺愫 2020-12-25 15:21

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 an

相关标签:
2条回答
  • 2020-12-25 15:37

    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.

    0 讨论(0)
  • 2020-12-25 15:53

    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]
    
    0 讨论(0)
提交回复
热议问题