sql – 选择一个select语句的select查询

前端之家收集整理的这篇文章主要介绍了sql – 选择一个select语句的select查询前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我甚至不知道我是否正确地做这个查询.
有一个三明治表有7个字段,其中2个是组合框(类型和面包).

所以我做了一个查询,将所有的组合框值合并成一个查询,如下所示:

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;

我现在得到这些表的平面值,我想计算每个TypesAndBreads.TBName下的所有三明治.我有这个,只是为了确保它适用于所有三明治:

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

但是我想引用子查询中的当前类型和TBName.这样的事情

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

但这当然不行.我不认为会这样,只是想尝试一下.我在考虑在VBA打开报告时可能会使用VBA构建查询.

所以我猜我的问题是:有没有办法引用子查询中当前选定的字段?还是有不同的方式来处理这个问题?

谢谢您的帮助

编辑:
我的表结构是这样的:

三明治的领域

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

其中三明治类型和面包是这些表的查找字段:

三明治类型的领域

| Sandwich Type |

面包的领域

| Bread |

TypesAndBreads查询结合了三明治类型和面包表,但是原因是这样,我可以得到具有该类型或面包的所有三明治的数量.这样的结果:

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

示例结果的第一行基本上说,有三十个三明治记录在三明治类型字段等于土耳其俱乐部.

我希望能够更好地解释.

解决方法

不知道Access是否支持它,但是在大多数引擎(包括sql Server)中,这被称为相关子查询并且可以正常工作:
SELECT  TypesAndBread.Type,(
        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

通过索引“类型”和“面包”并将子查询分布在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]
原文链接:https://www.f2er.com/mssql/82159.html

猜你在找的MsSQL相关文章