2

我需要从 Access DB 中提取总数量的产品数量,但包括供应商名称、ID 号、描述等......以及数量总和。

我有一个这样的查询:

SELECT [Vendor Name], SUM([Quantity]) AS Total
FROM [SalesDB]
WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) AND [Item Description] = 'bolts'
Group By [Vendor Name]

效果很好......除了我需要在查询中提取更多列,如下所示:

SELECT [Vendor Name], [Vendor No], [Item No], [Item Description], [Item Cost], [Quantity],  SUM([Quantity]) AS Total
FROM [SalesDB]
WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) AND [Item Description] = 'bolts'
Group By [Vendor Name]

不起作用,引发聚合错误

所以改为这样做:

SELECT [Vendor Name], [Vendor No], [Item No], [Item Description], [Item Cost], [Quantity],  SUM([Quantity]) AS Total
FROM [SalesDB]
WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) AND [Item Description] = 'bolts'
Group By [Vendor Name], [Vendor No], [Item No], [Item Description], [Item Cost], [Quantity]

哪个运行但改变结果太多。处理此查询的适当方法是什么?

4

2 回答 2

6

试试这个:

您必须将第一个查询作为派生表并与实际表连接以获取所有字段

    SELECT A.[Vendor Name], [Vendor No], [Item No], [Item Description], 
[Item Cost], [Quantity],B.Total
 from [SalesDB] A 
 inner join
    (SELECT [Vendor Name], SUM([Quantity]) AS Total
    FROM [SalesDB]
    WHERE [Vendor No] IN (1,2,3,4,5,6,7,8) 
    AND [Item Description] = 'bolts'
    Group By [Vendor Name])B
  on A.[Vendor Name]=B.[Vendor Name]
于 2012-07-31T06:33:11.760 回答
0

只是一个想法

SELECT 
        [ItemID],
        SUM(ItemQty) as 'QTY',
        [ItemName] as 'ItemName',
        itemPrice as 'itemPrice',
        SUM(ItemTotalPrice) as  'Total'
    FROM
        [OrderDetails]
        inner join Orders
        on [OrderDetails].OrderID=Orders.OrderID
         where Orders.TableID != 4
    GROUP BY  ItemID, [ItemName],itemPrice order by ItemID
于 2016-10-07T22:50:52.797 回答